﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Sockets;
using HDSmartCommunity.HDPlatform;
using System.Runtime.InteropServices;
using Timer = System.Timers.Timer;
using System.Timers;
using HDSmartCommunity.Models;
using HDSmartCommunity.DAL;
using System.Text;
using System.Net;
using HDSmartCommunity.BUS;
using Newtonsoft.Json;

namespace HDSmartCommunity.DevicePlatform
{
    public class DeviceSerialData
    {
        public SerialPort mySerialPort = new SerialPort();
        public SerialPort my485SerialPort_1 = new SerialPort();
        public SerialPort my485SerialPort_2 = new SerialPort();

        public MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions() { });//电梯状态缓存
        public static List<string> cmdlist = new List<string>();//发送命令队列
        public static int Elevatormode = -1;//电梯工作模式,0梯控，1普通
        public DateTime sendtime;//七合一面板心跳最新接收时间
        public int count_232 = 0;//未接收到232数据次数
        private static object locker = new object();
        private static readonly object replaylocker = new object();
        private static object tcplocker = new object();
        private static object basiclocker = new object();
        private static object statuslocker = new object();
        private static object slavesendlocker = new object();
        public bool status_232 = false;//232连接状态
        public static CancellationTokenSource tokenSource = new CancellationTokenSource();
        public CancellationToken token = tokenSource.Token;
        public ManualResetEvent resetEvent = new ManualResetEvent(true);
        public bool TcpAuthorize = false;//金茂平台是否下发进入梯控
        public int deviceid = 0;//设备号
        public Socket clientserver = null;
        public Thread clientthread = null;
        public static int ele_control = -1;//查询状态中梯控模式的值
        public static int _off = -1;//电源是否开启
        public List<int> phy_list = new List<int>();//物理楼层列表
        public List<string> show_list = new List<string>();//显示楼层列表
        public List<int> act_list = new List<int>();//实际楼层列表
        public string StatusCmd = string.Empty;//电梯状态命令
        public string SlaveStatus;//副梯状态命令
        public DateTime slavsendtime;//主梯接收到副梯状态最新时间

        public static string version_1 = "";
        Dictionary<string, Socket> dict = new Dictionary<string, Socket>(); //套接字集合

        Thread threadWatchCK = null; //负责串口监听客户端的线程
        Socket socketWatchCK = null; //负责串口监听客户端的套接字
        Dictionary<string, Socket> dictCK = new Dictionary<string, Socket>(); //串口套接字集合
        Socket socConnectionCK = null;//创建串口一个负责和客户端通信的套接字
        public int authmode;

        public bool masterFlag = false;
        public bool clientFlag = false;

        //创建 1个客户端套接字 和1个负责监听服务端请求的线程  
        // Socket socketClient = null;
        // Thread threadClient = null;

        public Timer slavetimer;
        public Timer mastertimer;
        public Timer sendtimer;
        public Timer ttyS0_sendtimer;
        public Timer ttyS1_sendtimer;

        public static bool SlaveConnect = false;//副梯监测是否连接主梯
        public bool MasterConnect = false;//主梯监测副梯连接状态
        public bool ismaster = false;//是否主梯
        public string mainIP;//主梯ip
        public int mainPort;//主梯端口号
        public int packet;//包号
        public int interval;//主副电梯发送间隔
        public int clink = -1;//上一次clink状态
        public int glink = -1;//上一次glink状态
        public int can = -1;//上一次can状态
        public HDProcessData devState;
        public string oldstatus = string.Empty;//电梯上一次状态
        public static DateTime statussend;//副梯发送状态时间
        public LogPrint logPrint;
        public int ttrAMA3_send = 0;
        public int ttrAMA3_receive = 0;
        public int ttrAMA1_receive = 0;
        public int ttrAMA2_receive = 0;
        public int sendport = 0;
        public int sign_can = 0;
        public static bool issend = false;
        public bool linkstatus = false;
        public bool mb_status = false;
        public int sign_kt = -1;
        public int hd_kt = -1;
        public int light = -1;
        public CurrentElevatorStatus currentElevatorStatus;
        public static List<string> ttyS0_cmdlist = new List<string>();//发送命令队列
        public static List<string> ttyS1_cmdlist = new List<string>();//发送命令队列
        public static bool issend_ttys1 = false;
        public string oldstatus_ttys0 = string.Empty;//ttys0电梯上一次状态
        public string oldstatus_ttys1 = string.Empty;//ttys1电梯上一次状态
        public static bool issend_ttys0 = false;
        private static object ttys0_locker = new object();

        public static CancellationTokenSource cmd_tokenSource = new CancellationTokenSource();
        public CancellationToken cmd_token = cmd_tokenSource.Token;
        public ManualResetEvent cmd_resetEvent = new ManualResetEvent(true);
        /// <summary>
        /// 设置 串口配置
        /// </summary>
        /// <param name="portName">串口号</param>
        /// <param name="baudRate">波特率</param>
        /// <param name="parity">校验位</param>
        /// <param name="dataBits">数据位</param>
        /// <param name="stopBits">停止位</param>
        private void SetSerialPortConfig(string portName, int baudRate, int parity, int dataBits, int stopBits)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                portName = $"/dev/{portName}";
            }
            // 串口 参数设置
            mySerialPort.PortName = portName;
            mySerialPort.BaudRate = baudRate;
            switch (parity)
            {
                case 0:
                default:
                    mySerialPort.Parity = Parity.None;
                    break;
                case 1:
                    mySerialPort.Parity = Parity.Odd;
                    break;
                case 2:
                    mySerialPort.Parity = Parity.Even;
                    break;
                case 3:
                    mySerialPort.Parity = Parity.Mark;
                    break;
                case 4:
                    mySerialPort.Parity = Parity.Space;
                    break;
            }
            mySerialPort.DataBits = ((4 < dataBits) && (dataBits < 9)) ? dataBits : 8;
            switch (stopBits)
            {
                case 0:
                    mySerialPort.StopBits = StopBits.None;
                    break;
                case 1:
                default:
                    mySerialPort.StopBits = StopBits.One;
                    break;
                case 2:
                    mySerialPort.StopBits = StopBits.OnePointFive;
                    break;
                case 3:
                    mySerialPort.StopBits = StopBits.Two;
                    break;
            }
            mySerialPort.ReadTimeout = -1;
            mySerialPort.RtsEnable = true;
            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceived);

            // 串口 接收数据处理定时器 参数设置
            SerialPortRecvTimer = new System.Timers.Timer();
            SerialPortRecvTimer.Interval = 100;
            SerialPortRecvTimer.AutoReset = false;
            SerialPortRecvTimer.Elapsed += new ElapsedEventHandler(SPRecvTimer_Tick);
        }

        private void Set485SerialPortConfig(string portName, int baudRate, int parity, int dataBits, int stopBits)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                portName = $"/dev/{portName}";
            }
            // 串口 参数设置
            my485SerialPort_1.PortName = portName;
            my485SerialPort_1.BaudRate = baudRate;
            switch (parity)
            {
                case 0:
                default:
                    my485SerialPort_1.Parity = Parity.None;
                    break;
                case 1:
                    my485SerialPort_1.Parity = Parity.Odd;
                    break;
                case 2:
                    my485SerialPort_1.Parity = Parity.Even;
                    break;
                case 3:
                    my485SerialPort_1.Parity = Parity.Mark;
                    break;
                case 4:
                    my485SerialPort_1.Parity = Parity.Space;
                    break;
            }
            my485SerialPort_1.DataBits = ((4 < dataBits) && (dataBits < 9)) ? dataBits : 8;
            switch (stopBits)
            {
                case 0:
                    my485SerialPort_1.StopBits = StopBits.None;
                    break;
                case 1:
                default:
                    my485SerialPort_1.StopBits = StopBits.One;
                    break;
                case 2:
                    my485SerialPort_1.StopBits = StopBits.OnePointFive;
                    break;
                case 3:
                    my485SerialPort_1.StopBits = StopBits.Two;
                    break;
            }
            //my485SerialPort_1.ReadTimeout = 200;
            my485SerialPort_1.RtsEnable = true;
            my485SerialPort_1.DataReceived += new SerialDataReceivedEventHandler(Data485Received_1);

            // 串口 接收数据处理定时器 参数设置
            SerialPortRecvTimer485_1 = new System.Timers.Timer();
            SerialPortRecvTimer485_1.Interval = 100;
            SerialPortRecvTimer485_1.AutoReset = false;
            SerialPortRecvTimer485_1.Elapsed += new ElapsedEventHandler(SP485RecvTimer_Tick_1);
        }

        private void Set485SerialPortConfig_2(string portName, int baudRate, int parity, int dataBits, int stopBits)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                portName = $"/dev/{portName}";
            }
            // 串口 参数设置
            my485SerialPort_2.PortName = portName;
            my485SerialPort_2.BaudRate = baudRate;
            switch (parity)
            {
                case 0:
                default:
                    my485SerialPort_2.Parity = Parity.None;
                    break;
                case 1:
                    my485SerialPort_2.Parity = Parity.Odd;
                    break;
                case 2:
                    my485SerialPort_2.Parity = Parity.Even;
                    break;
                case 3:
                    my485SerialPort_2.Parity = Parity.Mark;
                    break;
                case 4:
                    my485SerialPort_2.Parity = Parity.Space;
                    break;
            }
            my485SerialPort_2.DataBits = ((4 < dataBits) && (dataBits < 9)) ? dataBits : 8;
            switch (stopBits)
            {
                case 0:
                    my485SerialPort_2.StopBits = StopBits.None;
                    break;
                case 1:
                default:
                    my485SerialPort_2.StopBits = StopBits.One;
                    break;
                case 2:
                    my485SerialPort_2.StopBits = StopBits.OnePointFive;
                    break;
                case 3:
                    my485SerialPort_2.StopBits = StopBits.Two;
                    break;
            }
            my485SerialPort_2.ReadTimeout = -1;
            my485SerialPort_2.RtsEnable = true;
            my485SerialPort_2.DataReceived += new SerialDataReceivedEventHandler(Data485Received_2);

            // 串口 接收数据处理定时器 参数设置
            SerialPortRecvTimer485_2 = new Timer();
            SerialPortRecvTimer485_2.Interval = 100;
            SerialPortRecvTimer485_2.AutoReset = false;
            SerialPortRecvTimer485_2.Elapsed += new ElapsedEventHandler(SP485RecvTimer_Tick_2);
        }

        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="portName">串口号</param>
        /// <param name="baudRate">波特率</param>
        /// <param name="parity">校验位</param>
        /// <param name="dataBits">数据位</param>
        /// <param name="stopBits">停止位</param>
        public void OpenSerialPort(string portName, int baudRate, int parity, int dataBits, int stopBits)
        {
            try
            {
                SetSerialPortConfig(portName, baudRate, parity, dataBits, stopBits);
                mySerialPort.Open();
            }
            catch (Exception e)
            {
                logPrint.Log("ttyAMA3打开异常" + e.ToString());
            }
        }
        public void OpenttyS0SerialPort(string portName, int baudRate, int parity, int dataBits, int stopBits)
        {
            try
            {
                Set485SerialPortConfig(portName, baudRate, parity, dataBits, stopBits);
                my485SerialPort_1.Open();
                LogHelper.Log("ttyS0打开成功");
            }
            catch (Exception e)
            {
                LogHelper.Log("ttyS0打开异常" + e.ToString());
                logPrint.Log("ttyS0打开异常" + e.ToString());
            }
        }
        public void OpenttyS1SerialPort(string portName, int baudRate, int parity, int dataBits, int stopBits)
        {
            try
            {
                Set485SerialPortConfig_2(portName, baudRate, parity, dataBits, stopBits);
                my485SerialPort_2.Open();
            }
            catch (Exception e)
            {
                logPrint.Log("ttyS1打开异常" + e.ToString());
            }
        }

        /// <summary>
        /// 串口接收数据 位置
        /// </summary>
        private static int pSerialPortRecv = 0;
        private static int pSerialPortRecv_485_1 = 0;
        private static int pSerialPortRecv_485_2 = 0;
        /// <summary>
        /// 缓存区大小的长度    
        /// 缓冲区可调大
        /// （接收数据处理定时器 内接收数据量 小于下面设置的值即可）
        /// </summary>
        private static int byteLength = 40960;
        /// <summary>
        /// 串口接收字节 缓存区大小
        /// </summary>
        public byte[] byteSerialPortRecv = new byte[byteLength];
        public byte[] byteSerialPortRecv485_1 = new byte[byteLength];
        public byte[] byteSerialPortRecv485_2 = new byte[byteLength];

        /// <summary>
        /// 串口 接收数据处理定时器
        /// </summary>
        private Timer SerialPortRecvTimer;
        private Timer SerialPortRecvTimer485_1;
        private Timer SerialPortRecvTimer485_2;

        /// <summary>
        /// 广播 收到的数据 事件
        /// </summary>
        public event EventHandler<SerialPortRecvEventArgs> ReceivedDataEvent;
        public event EventHandler<SerialPort485_1RecvEventArgs> ReceivedDataEvent485_1;
        public event EventHandler<SerialPort485_2RecvEventArgs> ReceivedDataEvent485_2;
        /// <summary>
        /// 广播 收到的数据
        /// </summary>
        public class SerialPortRecvEventArgs : EventArgs
        {
            /// <summary>
            /// 广播 收到的串口数据
            /// </summary>
            public readonly byte[] RecvData = new byte[byteLength];

            /// <summary>
            /// 收到数据 的 长度
            /// </summary>
            public readonly int RecvDataLength;

            /// <summary>
            /// 将 收到的数据 转化成 待广播的数据
            /// </summary>
            public SerialPortRecvEventArgs(byte[] recvData, int recvDataLength)
            {
                recvData.CopyTo(RecvData, 0);
                RecvDataLength = recvDataLength;
            }
        }

        public class SerialPort485_1RecvEventArgs : EventArgs
        {
            /// <summary>
            /// 广播 收到的串口数据
            /// </summary>
            public readonly byte[] RecvData = new byte[byteLength];

            /// <summary>
            /// 收到数据 的 长度
            /// </summary>
            public readonly int RecvDataLength;

            /// <summary>
            /// 将 收到的数据 转化成 待广播的数据
            /// </summary>
            public SerialPort485_1RecvEventArgs(byte[] recvData, int recvDataLength)
            {
                recvData.CopyTo(RecvData, 0);
                RecvDataLength = recvDataLength;
            }
        }

        public class SerialPort485_2RecvEventArgs : EventArgs
        {
            /// <summary>
            /// 广播 收到的串口数据
            /// </summary>
            public readonly byte[] RecvData = new byte[byteLength];

            /// <summary>
            /// 收到数据 的 长度
            /// </summary>
            public readonly int RecvDataLength;

            /// <summary>
            /// 将 收到的数据 转化成 待广播的数据
            /// </summary>
            public SerialPort485_2RecvEventArgs(byte[] recvData, int recvDataLength)
            {
                recvData.CopyTo(RecvData, 0);
                RecvDataLength = recvDataLength;
            }
        }

        /// <summary>
        /// 数据处理定时器
        /// 定时检查缓冲区是否有数据，如果有数据则将数据处理并广播。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SPRecvTimer_Tick(object sender, EventArgs e)
        {
            byte[] TemporaryData = new byte[byteLength];
            int TemporaryDataLength = 0;

            if (ReceivedDataEvent != null)
            {
                byteSerialPortRecv.CopyTo(TemporaryData, 0);
                TemporaryDataLength = pSerialPortRecv;

                ReceivedDataEvent.Invoke(this, new SerialPortRecvEventArgs(TemporaryData, TemporaryDataLength));
                // 数据处理完后，将指针指向数据头，等待接收新的数据
                pSerialPortRecv = 0;
            }
        }

        private void SP485RecvTimer_Tick_1(object sender, EventArgs e)
        {
            byte[] TemporaryData = new byte[byteLength];
            int TemporaryDataLength = 0;

            if (ReceivedDataEvent485_1 != null)
            {
                byteSerialPortRecv485_1.CopyTo(TemporaryData, 0);
                TemporaryDataLength = pSerialPortRecv_485_1;

                ReceivedDataEvent485_1.Invoke(this, new SerialPort485_1RecvEventArgs(TemporaryData, TemporaryDataLength));
                // 数据处理完后，将指针指向数据头，等待接收新的数据
                pSerialPortRecv_485_1 = 0;
            }
        }

        private void SP485RecvTimer_Tick_2(object sender, EventArgs e)
        {
            byte[] TemporaryData = new byte[byteLength];
            int TemporaryDataLength = 0;

            if (ReceivedDataEvent485_2 != null)
            {
                byteSerialPortRecv485_2.CopyTo(TemporaryData, 0);
                TemporaryDataLength = pSerialPortRecv_485_2;

                ReceivedDataEvent485_2.Invoke(this, new SerialPort485_2RecvEventArgs(TemporaryData, TemporaryDataLength));
                // 数据处理完后，将指针指向数据头，等待接收新的数据
                pSerialPortRecv_485_2 = 0;
            }
        }

        #region 232数据接收

        /// <summary>
        /// 数据接收事件
        /// 串口收到数据后，关闭定时器，将收到的数据填入缓冲区，数据填入完毕后，开启定时器，等待下一次数据接收
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                SerialPortRecvTimer.Stop();
                byte[] ReadBuf = new byte[mySerialPort.BytesToRead];
                if (pSerialPortRecv > byteLength - ReadBuf.Length)
                {
                    pSerialPortRecv = 0;
                }
                mySerialPort.Read(ReadBuf, 0, ReadBuf.Length);
                ReadBuf.CopyTo(byteSerialPortRecv, pSerialPortRecv);
                pSerialPortRecv += ReadBuf.Length;

                string data = "ttrAMA3_receive:" + ToHexs(ReadBuf);
                CKSendMsg(data, ttrAMA3_receive);
                SerialPortRecvTimer.Start();
            }
            catch (Exception)
            {
                //throw;
            }
        }
        #endregion

        #region 485_1 梯控接收
        /* private void Data485Received_1(object sender, SerialDataReceivedEventArgs e)
         {
             try
             {
                 SerialPortRecvTimer485_1.Stop();

                 byte[] ReadBuf = new byte[my485SerialPort_1.BytesToRead];
                 if (pSerialPortRecv_485_1 > byteLength - ReadBuf.Length)
                 {
                     pSerialPortRecv_485_1 = 0;
                 }
                 my485SerialPort_1.Read(ReadBuf, 0, ReadBuf.Length);
                 ReadBuf.CopyTo(byteSerialPortRecv485_1, pSerialPortRecv_485_1);
                 pSerialPortRecv_485_1 += ReadBuf.Length;
                 SerialPortRecvTimer485_1.Start();

                 string data1 = "ttyAMA1_receive:" + ToHexs(ReadBuf);
                 LogHelper.Log(data1);
                 CKSendMsg(data1, ttrAMA1_receive);
                 bool result = true;
                 while (result)
                 {
                     try
                     {
                         for (int i = 0; i < byteSerialPortRecv485_1.Length; i++)
                         {
                             if (byteSerialPortRecv485_1[i] == 0x01 && byteSerialPortRecv485_1[i] == 0x03)
                             {
                                 string strCmd = string.Empty;
                                 int numcount = Convert.ToInt32(byteSerialPortRecv485_1[i + 1]);
                                 byte[] buffers = new byte[numcount + 2];
                                 for (int j = 0; j < numcount + 2; j++)
                                 {
                                     buffers[j] = byteSerialPortRecv485_1[i + j];
                                 }

                                 string data = ToHexs(buffers);
                                 string crcdata = CheckSum(data.Substring(3, data.Length - 6)).PadLeft(2, '0');
                                 if (data.Substring(data.Length - 2, 2) == crcdata)
                                 {
                                     string frameid = buffers[2].ToString("X").PadLeft(2, '0');
                                     string replay = string.Empty;
                                     Outcarevents outcarevents = new Outcarevents();
                                     if (buffers[3] == 0x01) //访客联动
                                     {
                                         outcarevents.cmd = "访客联动";
                                         outcarevents.ttrAMA1_data = data;
                                         if (buffers[4] == 0xEF)
                                         {
                                             //判断是否是主梯
                                             if (ismaster)//主梯发送
                                             {
                                                 logPrint.Log("访客联动主梯发送");
                                                 replay = VisitorLinkage(buffers, deviceid, frameid, outcarevents);
                                             }
                                             else//从梯，判断是否连接，连接不发送，不连接，到达间隔时间后后发送
                                             {
                                                 if (!QuerySlaveStatus())
                                                 {
                                                     logPrint.Log("访客联动副梯发送");
                                                     //Thread.Sleep(interval);
                                                     replay = VisitorLinkage(buffers, deviceid, frameid, outcarevents);
                                                 }
                                             }
                                         }
                                         else if (buffers[4] == deviceid)
                                         {
                                             replay = VisitorLinkage(buffers, deviceid, frameid, outcarevents);
                                         }
                                     }
                                     else if (buffers[3] == 0x02) //外呼
                                     {
                                         outcarevents.cmd = "外呼";
                                         outcarevents.ttrAMA1_data = data;
                                         if (buffers[4] == 0xEF)
                                         {
                                             //判断是否是主梯
                                             if (ismaster)//主梯发送
                                             {
                                                 logPrint.Log("外呼主梯发送");
                                                 replay = Outbound(buffers, deviceid, frameid, outcarevents);
                                             }
                                             else//从梯，判断是否连接，连接不发送，不连接，到达间隔时间后后发送
                                             {
                                                 if (!QuerySlaveStatus())
                                                 {
                                                     logPrint.Log("外呼副梯发送");
                                                     //Thread.Sleep(interval);
                                                     replay = Outbound(buffers, deviceid, frameid, outcarevents);
                                                 }
                                             }
                                         }
                                         else if (buffers[4] == deviceid)
                                         {
                                             replay = Outbound(buffers, deviceid, frameid, outcarevents);
                                         }

                                     }
                                     else if (buffers[3] == 0x03) //内呼授权
                                     {
                                         outcarevents.cmd = "内呼授权";
                                         outcarevents.ttrAMA1_data = data;
                                         if (buffers[4] == deviceid || buffers[4] == 0xFF)
                                         {
                                             replay = CallAuthorization(buffers, deviceid, frameid, outcarevents);
                                         }
                                     }
                                     else if (buffers[3] == 0x04)//内呼点亮
                                     {
                                         outcarevents.cmd = "内呼点亮";
                                         outcarevents.ttrAMA1_data = data;
                                         if (buffers[4] == deviceid)
                                         {
                                             replay = InternalCallOn(buffers, deviceid, frameid, outcarevents);
                                         }
                                     }
                                     else if (buffers[3] == 0x05)//查询状态
                                     {
                                         if (buffers[4] == 0xFF)
                                         {
                                             if (ismaster)//如果是主梯
                                             {
                                                 if (MasterConnect)//从梯连接，则主电梯回复主从状态
                                                 {
                                                     logPrint.Log("状态查询主梯发送主从所有状态");
                                                     if (!string.IsNullOrEmpty(StatusCmd) && !string.IsNullOrEmpty(SlaveStatus))
                                                     {
                                                         replay = "0F " + frameid + " 85 01 02 " + StatusCmd + " " + SlaveStatus;
                                                     }
                                                     else
                                                     {
                                                         replay = "05 " + frameid + " 85 00 02";
                                                     }
                                                 }
                                                 else//从梯不连接，主电梯回复自己的状态
                                                 {
                                                     logPrint.Log("状态查询主梯发送自己状态");
                                                     if (!string.IsNullOrEmpty(StatusCmd))
                                                     {
                                                         replay = "0A " + frameid + " 85 01 01 " + StatusCmd;
                                                     }
                                                     else
                                                     {
                                                         replay = "05 " + frameid + " 85 00 01";
                                                     }
                                                 }
                                             }
                                             else//从梯
                                             {
                                                 // if (!SlaveConnect)//从梯未连接,间隔固定时间后，自己发送状态
                                                 if (!QuerySlaveStatus())
                                                 {
                                                     logPrint.Log("状态查询副梯发送自己状态");
                                                     //Thread.Sleep(interval);
                                                     if (!string.IsNullOrEmpty(StatusCmd))
                                                     {
                                                         replay = "0A " + frameid + " 85 01 01 " + StatusCmd;
                                                     }
                                                     else
                                                     {
                                                         replay = "05 " + frameid + " 85 00 01";
                                                     }
                                                 }
                                             }
                                         }
                                         else if (buffers[4] == deviceid)
                                         {
                                             replay = "07 " + frameid + " 85 " + StatusCmd;
                                         }
                                     }
                                     else if (buffers[3] == 0x06)//延迟轿厢关门时间
                                     {
                                         if (buffers[4] == deviceid)
                                         {
                                             bool sendresult = SingleFloor(deviceid, 653, 1, 1);
                                             if (sendresult)
                                             {
                                                 replay = "04 " + frameid + " 86 01";
                                             }
                                             else
                                             {
                                                 replay = "04 " + frameid + " 86 00";
                                             }
                                         }
                                     }

                                     if (!string.IsNullOrEmpty(replay))
                                     {
                                         replay = replay.TrimEnd(' ');
                                         string crc = CheckSum(replay).PadLeft(2, '0');
                                         strCmd = "AA " + replay + " " + crc;
                                         my485SerialPort_1.Write(ToBytesSendDate(strCmd), 0, ToBytesSendDate(strCmd).Length);
                                     }
                                     Array.Clear(byteSerialPortRecv485_1, i, buffers.Length);
                                     result = false;
                                 }
                             }
                         }
                         result = false;
                     }
                     catch (Exception ex1)
                     {
                         result = false;
                     }
                 }
                 SerialPortRecvTimer485_1.Stop();
             }
             catch (Exception ex)
             {
                 //throw;
             }
         }*/

        List<byte> TmpDataReceived = new List<byte>();
        private void Data485Received_1(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                SerialPortRecvTimer485_1.Stop();

                byte[] ReadBuf = new byte[my485SerialPort_1.BytesToRead];
                if (pSerialPortRecv_485_1 > byteLength - ReadBuf.Length)
                {
                    pSerialPortRecv_485_1 = 0;
                }
                my485SerialPort_1.Read(ReadBuf, 0, ReadBuf.Length);
                ReadBuf.CopyTo(byteSerialPortRecv485_1, pSerialPortRecv_485_1);
                pSerialPortRecv_485_1 += ReadBuf.Length;
                SerialPortRecvTimer485_1.Start();

                string data1 = "ttyAMA1_receive:" + ToHexs(ReadBuf);
                //LogHelper.Log(data1);
                //CKSendMsg(data1, ttrAMA1_receive);
                bool result = true;
                /*while (result)
                {*/
                    try
                    {
                        for (int i = 0; i < byteSerialPortRecv485_1.Length; i++)
                        {
                            if (byteSerialPortRecv485_1[i] == 0x01 && byteSerialPortRecv485_1[i + 1] == 0x03 && byteSerialPortRecv485_1[i + 2] == 8)
                            {
                                string strCmd = string.Empty;
                                int numcount = Convert.ToInt32(byteSerialPortRecv485_1[i + 2]);
                                byte[] buffers = new byte[numcount + 5];
                                for (int j = 0; j < numcount + 5; j++)
                                {
                                    buffers[j] = byteSerialPortRecv485_1[i + j];
                                }

                                int length = buffers.Length;
                                byte[] crcdata = new byte[length - 2];
                                for (int k = 0; k < length - 2; k++)
                                {
                                    crcdata[k] = buffers[k];
                                }
                                byte[] crc = Crc18(crcdata);
                                if (crc[0] == buffers[length - 1] && crc[1] == buffers[length - 2])
                                {
                                    byte[] status = buffers.Skip(3).Take(8).ToArray();
                                    string newstatus = ToHexs(status);
                                    if (newstatus != oldstatus_ttys0)//状态与上一次不一致
                                    {
                                        //解析电梯状态数据
                                        //LogHelper.Log("电梯状态点：" + newstatus);
                                        CurrentElevatorStatus elevatorPoint = ProcessData(1, buffers);
                                        oldstatus_ttys0 = newstatus;
                                    }
                                    Array.Clear(byteSerialPortRecv485_1, i, buffers.Length);
                                    //result = false;
                                }
                            }
                            else if (byteSerialPortRecv485_1[i] == 0x01 && byteSerialPortRecv485_1[i + 1] == 0x10 && byteSerialPortRecv485_1[i + 5] == 0x01)
                            {

                                string strCmd = string.Empty;
                                byte[] buffers = new byte[8];
                                for (int j = 0; j < 8; j++)
                                {
                                    buffers[j] = byteSerialPortRecv485_1[i + j];
                                }
                                int length = buffers.Length;
                                byte[] crcdata = new byte[length - 2];
                                for (int k = 0; k < length - 2; k++)
                                {
                                    crcdata[k] = buffers[k];
                                }
                                byte[] crc = Crc18(crcdata);
                                if (crc[0] == buffers[length - 1] && crc[1] == buffers[length - 2])
                                {
                                    Array.Clear(byteSerialPortRecv485_1, i, buffers.Length);
                                    if (TmpDataReceived.Count > 500)
                                    {
                                        TmpDataReceived.RemoveRange(0, TmpDataReceived.Count - 200);
                                    }
                                    TmpDataReceived.AddRange(buffers);
                                }
                            }
                        }
                        result = false;
                    }
                    catch (Exception ex1)
                    {
                        result = false;
                    }
                //}
                SerialPortRecvTimer485_1.Stop();
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.ToString());
            }
        }

        #region 访客联动
        public string VisitorLinkage(byte[] buffers, int devid, string frameid, Outcarevents outcarevents)
        {
            string replay = string.Empty;
            int wh_direction = 631;//外呼方向，631上行；636下行
            List<int> floorarry = new List<int>();
            List<int> listphy = new List<int>();
            List<int> cu_floor = new List<int>();
            if (buffers[5] == 0xFF && buffers[6] == 0xFF)
            {
                for (int k = 1; k < 81; k++)
                {
                    floorarry.Add(k);
                }
            }
            else
            {
                string floorbinary = Convert.ToString(buffers[5], 2).PadLeft(8, '0') + Convert.ToString(buffers[6], 2).PadLeft(8, '0');
                bool isground = floorbinary.Substring(6, 1) == "0" ? true : false;
                int cur_floor = Convert.ToInt32(floorbinary.Substring(7, 9), 2);
                if (!isground)
                {
                    cur_floor = cur_floor * -1;
                }
                int count = Convert.ToInt32(buffers[7]);
                string frontfloor = string.Empty;
                for (int m = 1; m <= count; m++)
                {
                    string floorvalue = Reverse(Convert.ToString(buffers[8 + m], 2).PadLeft(8, '0'));
                    frontfloor += floorvalue;
                }

                listphy = ToPhyFloor(frontfloor); //目的楼层
                cu_floor = ToPhyFloorByact(cur_floor);//当前楼层

                if (cu_floor[0] > listphy[0])
                {
                    wh_direction = 636;
                }
            }
            string cmd = string.Empty;
            outcarevents.cmdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            bool sendresult = Floor(devid, wh_direction, 5, cu_floor, out cmd);
            outcarevents.ttrAMA3_data = cmd;
            if (sendresult)
            {
                bool message = Floor(devid, 601, 5, listphy, out cmd);
                outcarevents.ttrAMA3_data += ";" + cmd;
                if (message)
                {
                    outcarevents.result = "成功";
                    replay = "04 " + frameid + " 81 01";
                }
                else
                {
                    outcarevents.result = "失败";
                    replay = "04 " + frameid + " 81 00";
                }
            }
            else
            {
                outcarevents.result = "失败";
                replay = "04 " + frameid + " 81 00";
            }
            InsertOutcar(outcarevents);
            return replay;
        }
        #endregion

        #region 外呼
        public string Outbound(byte[] buffers, int devid, string frameid, Outcarevents outcarevents)
        {
            string replay = string.Empty;
            List<int> floorarry = new List<int>();

            if (buffers[5] == 0xFF && buffers[6] == 0xFF)
            {
                for (int m = 1; m < 81; m++)
                {
                    floorarry.Add(m);
                }
            }
            else
            {
                string floorbinary = Convert.ToString(buffers[5], 2).PadLeft(8, '0') + Convert.ToString(buffers[6], 2).PadLeft(8, '0');
                bool isground = floorbinary.Substring(6, 1) == "0" ? true : false;
                int phyfloor = Convert.ToInt32(floorbinary.Substring(7, 9), 2);
                if (!isground)
                {
                    phyfloor = phyfloor * -1;
                }

                floorarry = ToPhyFloorByact(phyfloor);
            }

            int startadd = 0;
            if (buffers[7] == 0x01)
            {
                startadd = 631;
            }
            else
            {
                startadd = 636;
            }
            string cmd = string.Empty;
            outcarevents.cmdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            bool sendresult = Floor(devid, startadd, 5, floorarry, out cmd);
            outcarevents.ttrAMA3_data = cmd;
            if (sendresult)
            {
                outcarevents.result = "成功";
                replay = "04 " + frameid + " 82 01";
            }
            else
            {
                outcarevents.result = "失败";
                outcarevents.reason = "命令下发失败";
                replay = "04 " + frameid + " 82 00";
            }
            InsertOutcar(outcarevents);
            return replay;
        }
        #endregion

        #region 内呼授权
        public string CallAuthorization(byte[] buffers, int devid, string frameid, Outcarevents outcarevents)
        {
            string replay = string.Empty;
            int count = Convert.ToInt32(buffers[5]);
            string frontfloor = string.Empty;
            for (int m = 1; m <= count; m++)
            {
                string floorvalue = Reverse(Convert.ToString(buffers[6 + m], 2).PadLeft(8, '0'));
                frontfloor = frontfloor + floorvalue;
            }

            List<int> listphy = ToPhyFloor(frontfloor);

            string cmd = string.Empty;
            outcarevents.cmdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            bool sendresult = Floor(devid, 611, 5, listphy, out cmd);
            outcarevents.ttrAMA3_data = cmd;
            if (sendresult)
            {
                outcarevents.result = "成功";
                replay = "04 " + frameid + " 83 01";
            }
            else
            {
                outcarevents.result = "失败";
                outcarevents.reason = "命令下发失败";
                replay = "04 " + frameid + " 83 00";
            }
            InsertOutcar(outcarevents);
            return replay;
        }
        #endregion

        #region 内呼点亮
        public string InternalCallOn(byte[] buffers, int devid, string frameid, Outcarevents outcarevents)
        {
            int count = Convert.ToInt32(buffers[5]);
            string frontfloor = string.Empty;
            for (int j = 1; j <= count; j++)
            {
                string floorvalue = Reverse(Convert.ToString(buffers[6 + j], 2).PadLeft(8, '0'));
                frontfloor += floorvalue;
            }
            List<int> listphy = ToPhyFloor(frontfloor);

            string cmd = string.Empty;
            outcarevents.cmdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            bool sendresult;
            if (Elevatormode == 0 && light == 0)
            {
                sendresult = Floor(devid, 611, 5, listphy, out cmd);
            }
            else
            {
                sendresult = Floor(devid, 621, 5, listphy, out cmd);

            }
            outcarevents.ttrAMA3_data = cmd;
            string replay;
            if (sendresult)
            {
                outcarevents.result = "成功";
                replay = "04 " + frameid + " 84 01";
            }
            else
            {
                outcarevents.result = "失败";
                outcarevents.reason = "未发送成功";
                replay = "04 " + frameid + " 84 00";
            }
            InsertOutcar(outcarevents);
            return replay;
        }
        #endregion

        #endregion

        #region 七合一面板接收
        private void Data485Received_2(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                SerialPortRecvTimer485_2.Stop();

                byte[] ReadBuf = new byte[my485SerialPort_2.BytesToRead];
                if (pSerialPortRecv_485_2 > byteLength - ReadBuf.Length)
                {
                    pSerialPortRecv_485_2 = 0;
                }
                my485SerialPort_2.Read(ReadBuf, 0, ReadBuf.Length);
                ReadBuf.CopyTo(byteSerialPortRecv485_2, pSerialPortRecv_485_2);
                pSerialPortRecv_485_2 += ReadBuf.Length;

                string data = "ttyAMA2_receive:" + ToHexs(ReadBuf);
                CKSendMsg(data, ttrAMA2_receive);

                bool result = true;
                while (result)
                {
                    try
                    {
                        for (int i = 0; i < byteSerialPortRecv485_2.Length; i++)
                        {
                            if (byteSerialPortRecv485_2[i] == 0xAA)
                            {
                                string strCmd = string.Empty;
                                int numcount = Convert.ToInt32(byteSerialPortRecv485_2[i + 1]);
                                byte[] buffers = new byte[numcount + 2];
                                for (int j = 0; j < numcount + 2; j++)
                                {
                                    buffers[j] = byteSerialPortRecv485_2[i + j];
                                }
                                string data1 = ToHexs(buffers);
                                string crcdata = CheckSum(data1.Substring(3, data1.Length - 6)).PadLeft(2, '0');
                                if (data1.Substring(data1.Length - 2, 2) == crcdata)
                                {
                                    string replay = string.Empty;
                                    int devid = buffers[2];
                                    if (buffers[3] == 0x11)
                                    {
                                        status_232 = true;
                                        if (status_232)
                                        {
                                            int credencetype = buffers[37];
                                            string uuid = string.Empty;
                                            for (int k = 0; k < 32; k++)
                                            {
                                                uuid += char.ConvertFromUtf32(buffers[5 + k]);
                                            }
                                            List<int> floorlist = new List<int>();
                                            VoucherInfo voucher = new VoucherInfo();
                                            Incarevents incarevents = new Incarevents();

                                            if (credencetype == 2)
                                            {
                                                string cardid = buffers[39].ToString("X").PadLeft(2, '0') + buffers[40].ToString("X").PadLeft(2, '0') + buffers[41].ToString("X").PadLeft(2, '0') + buffers[42].ToString("X").PadLeft(2, '0');
                                                voucher.CredenceType = credencetype;
                                                voucher.cardID = cardid;
                                                voucher.UUID = uuid;
                                            }
                                            else
                                            {
                                                voucher.CredenceType = credencetype;
                                                voucher.UUID = uuid;
                                            }
                                            VoucherInfo info = GetVoucherInfo(voucher);
                                            if (info == null)
                                            {
                                                logPrint.Log(string.Format("UUID为{0}未找到凭证信息", uuid));
                                                if (logPrint.GetPrint() == 1)
                                                {
                                                    CKSendMsg(string.Format("UUID为{0}未找到凭证信息", uuid), 1);
                                                }
                                                replay = "04 " + buffers[2].ToString("X").PadLeft(2, '0') + " 91 02";
                                            }
                                            else
                                            {
                                                info.CredenceType = credencetype;
                                                incarevents.ttrAMA2_data = data1;
                                                incarevents.UUID = info.UUID;
                                                incarevents.credenctype = info.CredenceType;
                                                if (!string.IsNullOrEmpty(info.StartTime) && !string.IsNullOrEmpty(info.OverTime))
                                                {
                                                    DateTime dt1 = Convert.ToDateTime(info.StartTime);
                                                    DateTime dt2 = Convert.ToDateTime(info.OverTime);
                                                    if (DateTime.Compare(DateTime.Now, dt1) > 0 && DateTime.Compare(dt2, DateTime.Now) > 0)
                                                    {
                                                        var list = info.elevatorAuthFloor.Split(',').ToList();

                                                        if (authmode == 1)
                                                        {
                                                            foreach (var item in list)
                                                            {
                                                                floorlist.Add(ToPhyFloorByact(Convert.ToInt32(item))[0]);
                                                            }
                                                        }
                                                        else if (authmode == 2)
                                                        {
                                                            foreach (var item in list)
                                                            {
                                                                floorlist.Add(GetPhyFloorByDisplay(item)[0]);
                                                            }
                                                        }

                                                        bool sendresult = false;
                                                        string cmd = string.Empty;
                                                        if (floorlist.Count > 1) //授权楼层是多层，内呼授权
                                                        {
                                                            sendresult = Floor(devid, 611, 5, floorlist, out cmd);
                                                            incarevents.operatetype = 2;
                                                        }
                                                        else if (floorlist.Count == 1)
                                                        {
                                                            ElevatorPoint elevatorPoint = new ElevatorPoint();
                                                            //电梯所在物理楼层
                                                            memoryCache.TryGetValue(devid, out elevatorPoint);
                                                            int ele_act_floor = elevatorPoint.physicalfloor;
                                                            logPrint.Log("当前楼层" + ele_act_floor);
                                                            int auth_floor = ToPhyFloorByact(Convert.ToInt32(list[0]))[0];
                                                            logPrint.Log("目的楼层" + auth_floor);
                                                            //授权楼层是单层,如果是人脸，下行则授权，上行则点亮，其余都点亮

                                                            if (credencetype == 7)
                                                            {
                                                                incarevents.cmdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                                                //人脸
                                                                if (auth_floor > ele_act_floor)
                                                                {
                                                                    //上行点亮
                                                                    if (Elevatormode == 0 && light == 0)
                                                                    {
                                                                        sendresult = Floor(devid, 611, 5, floorlist, out cmd);
                                                                    }
                                                                    else
                                                                    {
                                                                        sendresult = Floor(devid, 621, 5, floorlist, out cmd);
                                                                    }
                                                                    incarevents.operatetype = 1;
                                                                }
                                                                else
                                                                {
                                                                    incarevents.operatetype = 2;
                                                                    //下行授权
                                                                    sendresult = Floor(devid, 611, 5, floorlist, out cmd);
                                                                }
                                                            }
                                                            else
                                                            {
                                                                sendresult = Floor(devid, 611, 5, floorlist, out cmd);
                                                            }
                                                        }
                                                        else
                                                        {
                                                            replay = "04 " + buffers[2].ToString("X").PadLeft(2, '0') + " 91 02";
                                                        }
                                                        incarevents.cmdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                                        incarevents.ttrAMA3_data = cmd;
                                                        if (sendresult)
                                                        {
                                                            incarevents.result = "success";
                                                            replay = "04 " + buffers[2].ToString("X").PadLeft(2, '0') + " 91 01";
                                                        }
                                                        else
                                                        {
                                                            incarevents.result = "fail";
                                                            incarevents.reason = "232发送失败";
                                                            replay = "04 " + buffers[2].ToString("X").PadLeft(2, '0') + " 91 00";
                                                        }
                                                        //如果电梯开关关闭
                                                        if (_off == 0)
                                                        {
                                                            replay = "04 " + buffers[2].ToString("X").PadLeft(2, '0') + " 91 03";
                                                        }
                                                        else if (!mb_status)//面板不通讯
                                                        {
                                                            replay = "04 " + buffers[2].ToString("X").PadLeft(2, '0') + " 91 04";
                                                        }

                                                        InsertIncar(incarevents);
                                                    }
                                                    else
                                                    {
                                                        logPrint.Log(string.Format("UUID为{0}不在时间段内", uuid));
                                                        if (logPrint.GetPrint() == 1)
                                                        {
                                                            CKSendMsg(string.Format("UUID为{0}不在时间段内", uuid), 1);
                                                        }
                                                        replay = "04 " + buffers[2].ToString("X").PadLeft(2, '0') + " 91 07";
                                                    }
                                                }
                                                else
                                                {
                                                    if (logPrint.GetPrint() == 1)
                                                    {
                                                        CKSendMsg(string.Format("UUID为{0}不在时间段内", uuid), 1);
                                                    }
                                                    replay = "04 " + buffers[2].ToString("X").PadLeft(2, '0') + " 91 07";
                                                }
                                                info.UUID = uuid;
                                                //电梯乘梯事件上报
                                                if (authmode == 1)
                                                {
                                                    IncidentReporting(info);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (logPrint.GetPrint() == 1)
                                            {
                                                CKSendMsg(string.Format("电梯未连接"), 1);
                                            }
                                            replay = "04 " + buffers[2].ToString("X").PadLeft(2, '0') + " 91 03";
                                        }
                                    }
                                    else if (buffers[3] == 0x12)
                                    {
                                        sendtime = DateTime.Now;

                                        if (buffers[26] == 0 && buffers[27] == 0)
                                        {
                                            mb_status = true;
                                            if (TcpAuthorize)//金茂进入梯控
                                            {
                                                if (Elevatormode == 1)//普通模式下,收到心跳后，由普通变为授权
                                                {
                                                    LadderControl(devid);
                                                    ModeRecord mode = new ModeRecord();
                                                    mode.workmode = 0;
                                                    mode.updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                                    mode.reason = "重新收到心跳，切换为授权模式";
                                                    InsertModeRecord(mode);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            mb_status = false;
                                            if (TcpAuthorize)//金茂进入梯控
                                            {
                                                if (Elevatormode == 0)//故障，由授权改为普通
                                                {
                                                    ExitLadderControl(devid);
                                                    sign_kt = -1;
                                                    ModeRecord mode = new ModeRecord();
                                                    mode.workmode = 1;
                                                    mode.updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                                    mode.reason = "收到故障信号，切换为普通模式";
                                                    InsertModeRecord(mode);
                                                }
                                            }
                                        }
                                    }
                                    if (!string.IsNullOrEmpty(replay))
                                    {
                                        string crc = CheckSum(replay).PadLeft(2, '0');
                                        strCmd = "AA " + replay + " " + crc;
                                        my485SerialPort_2.Write(ToBytesSendDate(strCmd), 0, ToBytesSendDate(strCmd).Length);
                                    }
                                    Array.Clear(byteSerialPortRecv485_2, i, buffers.Length);
                                    result = false;
                                }
                            }
                        }
                        result = false;
                    }
                    catch (Exception ex)
                    {
                        result = false;
                    }
                }
                SerialPortRecvTimer485_2.Start();
            }
            catch (Exception)
            {
            }
        }

        public void InsertIncar(Incarevents incarevents)
        {
            DeviceDAL da = new DeviceDAL();
            da.InsertIncar(incarevents);
        }
        public void InsertOutcar(Outcarevents outcarevents)
        {
            DeviceDAL da = new DeviceDAL();
            da.InsertOutcar(outcarevents);
        }

        public void InsertModeRecord(ModeRecord modeRecord)
        {
            DeviceDAL da = new DeviceDAL();
            da.InsertModeRecord(modeRecord);
        }

        public void InsertEquipment(Equipment equipment)
        {
            DeviceDAL da = new DeviceDAL();
            da.InsertEquipment(equipment);
        }

        public void IncidentReporting(VoucherInfo info)
        {
            Incident incident = new Incident();
            incident.UUID = info.UUID;
            incident.credenceNo = info.cardID;
            incident.RecordType = GetRecordType(info.CredenceType);
            incident.CredenceType = Convert.ToInt32(info.CredenceType);
            string[] strArray = info.elevatorAuthFloor.Split(new char[] { ',' });
            incident.DestFloor = Array.ConvertAll<string, int>(strArray, s => int.Parse(s));
            incident.opTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            devState.IncidentReporting(incident);
        }

        public int GetRecordType(int type)
        {
            int RecordType;
            switch (type)
            {
                case 7:
                    RecordType = 30000;
                    break;
                case 6:
                    RecordType = 30004;
                    break;
                case 2:
                    RecordType = 30002;
                    break;
                case 10:
                    RecordType = 30005;
                    break;
                case 8:
                    RecordType = 30003;
                    break;
                case 9:
                    RecordType = 30001;
                    break;
                default:
                    RecordType = 0;
                    break;
            }
            return RecordType;
        }
        #endregion

        #region 字符串倒置
        public static string Reverse(string str)
        {
            char[] arr = str.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }
        #endregion

        #region byte转十六进制
        public string ToHexs(byte[] data)
        {
            if (data.Length <= 0) return "";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i].ToString("X2"));
                sb.Append(" ");
            }
            string str = sb.ToString();
            return str.Substring(0, str.Length - 1);
        }
        #endregion

        #region CRC校验
        public byte[] Crc18(byte[] buffer, int start = 0, int len = 0)
        {
            if (buffer == null || buffer.Length == 0) return null;
            if (start < 0) return null;
            if (len == 0) len = buffer.Length - start;
            int length = start + len;
            if (length > buffer.Length) return null;
            ushort crc = 0xFFFF;// Initial value
            for (int i = start; i < length; i++)
            {
                crc ^= buffer[i];
                for (int j = 0; j < 8; j++)
                {
                    if ((crc & 1) > 0)
                        crc = (ushort)((crc >> 1) ^ 0xA001);// 0xA001 = reverse 0x8005
                    else
                        crc = (ushort)(crc >> 1);
                }
            }
            byte[] ret = BitConverter.GetBytes(crc);
            Array.Reverse(ret);
            return ret;
        }
        #endregion

        #region 截取数据
        public byte[] GetReadData(byte[] buffer, int devid)
        {
            byte[] data = GetData(buffer, devid);
            if (data != null)
            {
                int length = data.Length;
                byte[] crcdata = new byte[length - 2];
                for (int i = 0; i < length - 2; i++)
                {
                    crcdata[i] = data[i];
                }
                byte[] crc = Crc18(crcdata);
                if (crc[0] == data[length - 1] && crc[1] == data[length - 2])
                {
                    //LogHelper.Log("rs232 replay:"+ToHexs(data));
                    return data;
                }
            }
            return null;
        }

        public byte[] GetReadttyS0Data(byte[] buffer, int devid)
        {
            byte[] data = GetttyS0Data(buffer, devid);
            if (data != null)
            {
                int length = data.Length;
                byte[] crcdata = new byte[length - 2];
                for (int i = 0; i < length - 2; i++)
                {
                    crcdata[i] = data[i];
                }
                byte[] crc = Crc18(crcdata);
                if (crc[0] == data[length - 1] && crc[1] == data[length - 2])
                {
                    LogHelper.Log("rs232 replay:" + ToHexs(data));
                    return data;
                }
            }
            return null;
        }

        public byte[] GetReadttyS1Data(byte[] buffer, int devid)
        {
            byte[] data = GetttyS1Data(buffer, devid);
            if (data != null)
            {
                int length = data.Length;
                byte[] crcdata = new byte[length - 2];
                for (int i = 0; i < length - 2; i++)
                {
                    crcdata[i] = data[i];
                }
                byte[] crc = Crc18(crcdata);
                if (crc[0] == data[length - 1] && crc[1] == data[length - 2])
                {
                    //LogHelper.Log("rs232 replay:"+ToHexs(data));
                    return data;
                }
            }
            return null;
        }

        public byte[] GetData(byte[] buffer, int devid)
        {
            for (int i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] == devid && buffer[i + 1] == 0x03 && buffer[i + 2] == 12)
                {
                    string a = buffer[i + 2].ToString("X2").PadLeft(2, '0');
                    int num = int.Parse(a, System.Globalization.NumberStyles.HexNumber);
                    byte[] data = new byte[num + 5];
                    int n = 0;
                    for (int j = i; j < i + num + 5; j++)
                    {
                        data[n] = buffer[j];
                        n++;
                    }
                    Array.Clear(byteSerialPortRecv, i, data.Length);

                    return data;
                }
            }
            return null;
        }

        public byte[] GetttyS0Data(byte[] buffer, int devid)
        {
            for (int i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] == devid && buffer[i + 1] == 0x03 && buffer[i + 2] == 12)
                {
                    string a = buffer[i + 2].ToString("X2").PadLeft(2, '0');
                    int num = int.Parse(a, System.Globalization.NumberStyles.HexNumber);
                    byte[] data = new byte[num + 5];
                    int n = 0;
                    for (int j = i; j < i + num + 5; j++)
                    {
                        data[n] = buffer[j];
                        n++;
                    }
                    Array.Clear(byteSerialPortRecv485_1, i, data.Length);

                    return data;
                }
            }
            return null;
        }

        public byte[] GetttyS1Data(byte[] buffer, int devid)
        {
            for (int i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] == devid && buffer[i + 1] == 0x03 && buffer[i + 2] == 12)
                {
                    string a = buffer[i + 2].ToString("X2").PadLeft(2, '0');
                    int num = int.Parse(a, System.Globalization.NumberStyles.HexNumber);
                    byte[] data = new byte[num + 5];
                    int n = 0;
                    for (int j = i; j < i + num + 5; j++)
                    {
                        data[n] = buffer[j];
                        n++;
                    }
                    Array.Clear(byteSerialPortRecv485_2, i, data.Length);

                    return data;
                }
            }
            return null;
        }

        #endregion

        #region 获取设备状态

        public bool GetBasicData(int devid)
        {
            lock (basiclocker)
            {
                while (true)
                {
                    try
                    {
                        devid = 1;
                        string data = string.Empty;
                        byte[] buffer = byteSerialPortRecv;
                        byte[] crcdata = GetReadData(buffer, devid);
                        if (crcdata != null)
                        {
                            byte[] status = crcdata.Skip(3).Take(12).ToArray();
                            string newstatus = ToHexs(status);
                            if (newstatus != oldstatus)//状态与上一次不一致
                            {
                                //解析电梯状态数据
                                ElevatorPoint elevatorPoint = ParsingData(devid, crcdata);
                                if (TcpAuthorize)
                                {
                                    if (ele_control == Elevatormode && ele_control == 0)//电梯梯控状态与上一次断开前状态不一致
                                    {
                                        logPrint.Log("当前梯控状态与金茂不一致");
                                        bool result = LadderControl(devid);//进入梯控
                                        if (result)
                                        {
                                            ModeRecord mode = new ModeRecord();
                                            mode.workmode = 0;
                                            mode.updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                            mode.reason = "电梯状态和金茂平台下发不一致";
                                            InsertModeRecord(mode);
                                        }
                                    }
                                }

                                //判断clink、glink、can、丢包数是否变化
                                if (packet != elevatorPoint.packet)
                                {
                                    if (UpdatePacketStatus(elevatorPoint.packet))
                                    {
                                        packet = elevatorPoint.packet;
                                    }
                                }

                                if (clink != elevatorPoint.clink)
                                {
                                    logPrint.Log("clink状态变更为" + elevatorPoint.clink);
                                    clink = elevatorPoint.clink;
                                }

                                if (can != elevatorPoint.can)
                                {
                                    logPrint.Log("can状态变更为" + elevatorPoint.can);
                                    can = elevatorPoint.can;
                                }

                                if (glink != elevatorPoint.glink)
                                {
                                    logPrint.Log("can状态变更为" + elevatorPoint.can);
                                    glink = elevatorPoint.glink;
                                }

                                data += deviceid.ToString("X").PadLeft(2, '0');
                                if (elevatorPoint.up == 1)
                                {
                                    data += " 01";
                                }
                                else if (elevatorPoint.down == 1)
                                {
                                    data += " 02";
                                }
                                else if (elevatorPoint.falut == 1)
                                {
                                    data += " 80";
                                }
                                else if (elevatorPoint.up == 0 && elevatorPoint.down == 0)
                                {
                                    data += " 00";
                                }

                                if (elevatorPoint.frontdooropening == 1)
                                {
                                    data += " 10";
                                }
                                else if (elevatorPoint.frontdooropened == 1)
                                {
                                    data += " 11";
                                }
                                else if (elevatorPoint.frontdoorcloseing == 1)
                                {
                                    data += " 12";
                                }
                                else if (elevatorPoint.frontdoorclosed == 1)
                                {
                                    data += " 13";
                                }
                                else
                                {
                                    data += " 80";
                                }

                                if (elevatorPoint.physicalfloor == 0)
                                {
                                    data += " 00 00";
                                }
                                else
                                {
                                    List<int> show_floor_list = ToActFloorByPhy(elevatorPoint.physicalfloor);
                                    string value = string.Empty;
                                    if (show_floor_list[0] > 0)
                                    {
                                        value = "0000000" + Convert.ToString(show_floor_list[0], 2).PadLeft(9, '0');
                                    }
                                    else
                                    {
                                        value = "0000001" + Convert.ToString(Math.Abs(show_floor_list[0]), 2).PadLeft(9, '0');
                                    }
                                    data += " " + string.Format("{0:X}", Convert.ToInt32(value.Substring(0, 8), 2)).PadLeft(2, '0') + " " + string.Format("{0:X}", Convert.ToInt32(value.Substring(8, 8), 2)).PadLeft(2, '0');
                                }
                                StatusCmd = data;
                                //副电梯，通过Tcp发送至主电梯
                                if (!ismaster)
                                {
                                    logPrint.Log("电梯状态变更,发送给主梯");
                                    SlaveCmdSend(StatusCmd);
                                }

                                oldstatus = newstatus;

                                return true;
                            }
                            else
                            {
                                if (!ismaster)//数据状态与上一次相同，5s发送一次
                                {
                                    if (SlaveStatusCmd() > 5000)
                                    {
                                        SlaveCmdSend(StatusCmd);
                                    }
                                }
                                return true;
                            }
                        }
                        else
                        {
                            return false;
                        }
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                }
            }
        }

        //获取基础数据-金茂项目
        public bool GetttyS0BasicData(int devid)
        {
            lock (basiclocker)
            {
                while (true)
                {
                    try
                    {
                        //devid = 1;
                        string data = string.Empty;
                        byte[] buffer = byteSerialPortRecv485_1;
                        byte[] crcdata = GetReadttyS0Data(buffer, devid);
                        if (crcdata != null)
                        {
                            byte[] status = crcdata.Skip(3).Take(8).ToArray();
                            string newstatus = ToHexs(status);
                            //LogHelper.Log("电梯状态" + newstatus);
                            if (newstatus != oldstatus_ttys0)//状态与上一次不一致
                            {
                                //解析电梯状态数据
                                CurrentElevatorStatus elevatorPoint = ProcessData(devid, crcdata);
                                /* if (TcpAuthorize)
                                 {
                                     if (ele_control == Elevatormode && ele_control == 0)//电梯梯控状态与上一次断开前状态不一致
                                     {
                                         logPrint.Log("当前梯控状态与金茂不一致");
                                         bool result = LadderControl(devid);//进入梯控
                                         if (result)
                                         {
                                             ModeRecord mode = new ModeRecord();
                                             mode.workmode = 0;
                                             mode.updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                             mode.reason = "电梯状态和金茂平台下发不一致";
                                             InsertModeRecord(mode);
                                         }
                                     }
                                 }*/


                                oldstatus_ttys0 = newstatus;

                                return true;
                            }
                        }
                        else
                        {
                            return false;
                        }
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                }
            }
        }

        public bool GetttyS1BasicData(int devid)
        {
            lock (basiclocker)
            {
                while (true)
                {
                    try
                    {
                        string data = string.Empty;
                        byte[] buffer = byteSerialPortRecv485_2;
                        byte[] crcdata = GetReadttyS1Data(buffer, devid);
                        if (crcdata != null)
                        {
                            byte[] status = crcdata.Skip(3).Take(12).ToArray();
                            string newstatus = ToHexs(status);
                            if (newstatus != oldstatus_ttys1)//状态与上一次不一致
                            {
                                //解析电梯状态数据
                                CurrentElevatorStatus elevatorPoint = ProcessData(devid, crcdata);

                                oldstatus_ttys1 = newstatus;

                                return true;
                            }
                        }
                        else
                        {
                            return false;
                        }
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                }
            }
        }

        public void SlaveCmdSend(string cmd)
        {
            lock (slavesendlocker)
            {
                SendToServer(cmd);
            }
        }

        public ElevatorPoint ParsingData(int devid, byte[] crcdata)
        {
            ElevatorPoint elevatorPoint = new ElevatorPoint();
            try
            {
                //电梯物理楼层 40001
                elevatorPoint.physicalfloor = Convert.ToInt32(crcdata[4].ToString().PadLeft(2, '0'));
                byte[] floorbuffer = new byte[2];
                floorbuffer[0] = crcdata[5];
                floorbuffer[1] = crcdata[6];
                string _showfloor = HexToString(floorbuffer);
                //电梯显示楼层 40002
                if (floorbuffer[0] == 0 && floorbuffer[1] == 0)
                {
                    elevatorPoint.Showfloor = "0";
                }
                else
                {
                    if (_showfloor.Substring(0, 1) == "0")
                    {
                        elevatorPoint.Showfloor = _showfloor.Substring(1, 1);
                    }
                    else
                    {
                        elevatorPoint.Showfloor = _showfloor;
                    }
                }

                //电梯运行点位40003
                string point_run_h = Convert.ToString(crcdata[7], 2).PadLeft(8, '0');
                string point_run_l = Convert.ToString(crcdata[8], 2).PadLeft(8, '0');
                elevatorPoint.up = Convert.ToInt32(point_run_l.Substring(7, 1));
                elevatorPoint.down = Convert.ToInt32(point_run_l.Substring(6, 1));
                elevatorPoint.frontdooropening = Convert.ToInt32(point_run_l.Substring(5, 1));
                elevatorPoint.frontdooropened = Convert.ToInt32(point_run_l.Substring(4, 1));
                elevatorPoint.frontdoorcloseing = Convert.ToInt32(point_run_l.Substring(3, 1));
                elevatorPoint.frontdoorclosed = Convert.ToInt32(point_run_l.Substring(2, 1));
                elevatorPoint.behinddooropening = Convert.ToInt32(point_run_l.Substring(1, 1));
                elevatorPoint.behinddooropened = Convert.ToInt32(point_run_l.Substring(0, 1));
                elevatorPoint.behinddoorcloseing = Convert.ToInt32(point_run_h.Substring(7, 1));
                elevatorPoint.behinddoorclosed = Convert.ToInt32(point_run_h.Substring(6, 1));
                elevatorPoint.falut = Convert.ToInt32(point_run_h.Substring(5, 1));
                elevatorPoint.overhaul = Convert.ToInt32(point_run_h.Substring(4, 1));
                elevatorPoint.fire = Convert.ToInt32(point_run_h.Substring(3, 1));
                //电梯状态点位40004
                string point_status_l = Convert.ToString(crcdata[10], 2).PadLeft(8, '0');
                elevatorPoint.glink = Convert.ToInt32(point_status_l.Substring(7, 1));
                elevatorPoint.clink = Convert.ToInt32(point_status_l.Substring(6, 1));
                elevatorPoint.can = Convert.ToInt32(point_status_l.Substring(5, 1));
                elevatorPoint.control = Convert.ToInt32(point_status_l.Substring(4, 1));
                if (_off != Convert.ToInt32(point_status_l.Substring(3, 1)))
                {
                    _off = Convert.ToInt32(point_status_l.Substring(3, 1));
                }
                ele_control = elevatorPoint.control;

                if (elevatorPoint.clink == 1 || elevatorPoint.can == 1)
                {
                    linkstatus = true;
                }
                else
                {
                    linkstatus = false;
                }

                //版本40005
                int count_version = Convert.ToInt32(crcdata[11].ToString().PadLeft(2, '0') + crcdata[12].ToString().PadLeft(2, '0'));//转化为十进制

                string version = count_version.ToString();
                elevatorPoint.version = version.Substring(0, version.Length - 2) + "." + version.Substring(version.Length - 2, 2);
                version_1 = elevatorPoint.version;
                //丢包数40006
                int count_pack = Convert.ToInt32(crcdata[13].ToString().PadLeft(2, '0')) + Convert.ToInt32(crcdata[14].ToString().PadLeft(2, '0'));//转化为十进制
                elevatorPoint.packet = count_pack;
                memoryCache.Set(deviceid, elevatorPoint);
                return elevatorPoint;
            }
            catch
            {
                return elevatorPoint;
            }
        }

        public CurrentElevatorStatus ProcessData(int devid, byte[] crcdata)
        {
            //ElevatorPoint elevatorPoint = new ElevatorPoint();
            CurrentElevatorStatus currentElevatorStatus = new CurrentElevatorStatus();
            try
            {
                //电梯物理楼层 40001
                currentElevatorStatus.PhysicalFloor = Convert.ToInt32(crcdata[4].ToString().PadLeft(2, '0'));
                byte[] floorbuffer = new byte[2];
                floorbuffer[0] = crcdata[5];
                floorbuffer[1] = crcdata[6];
                string _showfloor = HexToString(floorbuffer);
                //电梯显示楼层 40002
                if (floorbuffer[0] == 0 && floorbuffer[1] == 0)
                {
                    currentElevatorStatus.DisplayFloor = "0";
                }
                else
                {
                    if (_showfloor.Substring(0, 1) == "0")
                    {
                        currentElevatorStatus.DisplayFloor = _showfloor.Substring(1, 1);
                    }
                    else
                    {
                        currentElevatorStatus.DisplayFloor = _showfloor;
                    }
                }
                //电梯运行点位40003
                string point_run_h = Convert.ToString(crcdata[7], 2).PadLeft(8, '0');
                string point_run_l = Convert.ToString(crcdata[8], 2).PadLeft(8, '0');
                currentElevatorStatus.Up = Convert.ToInt32(point_run_l.Substring(7, 1));
                currentElevatorStatus.Down = Convert.ToInt32(point_run_l.Substring(6, 1));
                currentElevatorStatus.Open = Convert.ToInt32(point_run_l.Substring(5, 1));
                currentElevatorStatus.Close = Convert.ToInt32(point_run_l.Substring(4, 1));
                currentElevatorStatus.Fault = Convert.ToInt32(point_run_l.Substring(3, 1));
                string state = JsonConvert.SerializeObject(currentElevatorStatus);
                CurrentElevatorStatus currentElevator_old = new CurrentElevatorStatus();
                memoryCache.TryGetValue(deviceid, out currentElevator_old);
                if (currentElevator_old != null)
                {
                    if (currentElevator_old.Fault != currentElevatorStatus.Fault)
                    {
                        if (currentElevatorStatus.Fault == 1)
                        {
                            LogHelper.Log("电梯故障");
                        }
                        else if (currentElevatorStatus.Fault == 0)
                        {
                            LogHelper.Log("电梯恢复故障");
                        }
                    }
                }

                memoryCache.Set(deviceid, currentElevatorStatus);
                return currentElevatorStatus;
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString());
                return currentElevatorStatus;
            }
        }
        #endregion

        #region 232发送
        public bool SendMsg(string data)
        {
            try
            {
                if (data != "01 03 00 00 00 06 C5 C8")
                {
                    logPrint.Log(data);
                }
                mySerialPort.Write(ToBytesSendDate(data), 0, ToBytesSendDate(data).Length);
                data = "ttrAMA3_send" + data;

                CKSendMsg(data, ttrAMA3_send);
                return true;
            }
            catch (Exception e)
            {
                //logPrint.Log(data + "命令发送失败");
                return false;
            }
        }

        public bool ttyS0SendMsg(string data)
        {
            try
            {
                my485SerialPort_1.Write(ToBytesSendDate(data), 0, ToBytesSendDate(data).Length);
                if (data != "01 03 00 00 00 04 44 09")
                {
                    logPrint.Log("电梯发送成功" + data);
                }
                data = "ttyS0_send:" + data;
                //LogHelper.Log(data);
                //CKSendMsg(data, ttrAMA3_send);
                return true;
            }
            catch (Exception e)
            {
                LogHelper.Log("命令发送失败" + data + e.ToString());
                logPrint.Log(data + "命令发送失败" + e.ToString());
                return false;
            }
        }

        public bool ttyS1SendMsg(string data)
        {
            try
            {
                if (data != "02 03 00 00 00 04 44 3A")
                {
                    logPrint.Log(data);
                }
                my485SerialPort_2.Write(ToBytesSendDate(data), 0, ToBytesSendDate(data).Length);
                data = "ttrAMA3_send" + data;

                CKSendMsg(data, ttrAMA3_send);
                return true;
            }
            catch (Exception e)
            {
                //logPrint.Log(data + "命令发送失败");
                return false;
            }
        }

        public static byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }

        public byte[] ToBytesSendDate(string str)
        {
            List<byte> result = new List<byte>();
            if (str.Contains(" "))
            {
                string[] strs = str.Trim().Split(' ');
                foreach (string s in strs)
                {
                    result.Add(Convert.ToByte(s.Trim(), 16));
                }
            }
            else
            {
                result.Add(Convert.ToByte(str, 16));
            }
            return result.ToArray();
        }
        #endregion

        #region RS232发送数据
        /* public bool Send232Msg(string data, int devid, int add, int count)
         {
             lock (sendlocker)
             {
                 bool result = false;
                 int sendtime = 0;
                 cmdlist.Add(data);
                 logPrint.Log("向队列添加发送任务");

                 while (sendtime < 3)
                 {
                     if (SendMsg(data))
                     {
                         logPrint.Log("第" + sendtime.ToString() + "发送任务");

                         if (GetSendSuccess(devid, add, count))
                         {
                             logPrint.Log("接受成功,向队列移除发送任务");
                             cmdlist.Remove(data);
                             return true;
                         }
                         else
                         {
                             sendtime++;
                             //Thread.Sleep(200);
                         }
                         return true;
                     }
                     else
                     {
                         sendtime++;
                         //Thread.Sleep(200);
                     }
                 }
                 logPrint.Log("发送3次无回复,向队列移除发送任务");
                 cmdlist.Remove(data);

                 return result;
             }
         }*/

        public bool SendTiming()
        {
            return true;
        }

        #endregion

        #region 外呼、内呼、权限
        public bool Floor(int devid, int add, int count, List<int> floor, out string cmd)
        {
            cmd = string.Empty;
            try
            {
                string strcmd = string.Empty;
                string strbyte = string.Empty;
                string strbit = string.Empty;
                for (int i = 1; i < 81; i++)
                {
                    var res1 = floor.Any(e => e == i);
                    if (!res1)
                    {
                        strbit = strbit + "0";
                    }
                    else
                    {
                        strbit = strbit + "1";
                    }
                }
                strbit = Reverse(strbit);

                strcmd = Convert.ToInt32(strbit.Substring(64, 8), 2).ToString("X").PadLeft(2, '0') + " " + Convert.ToInt32(strbit.Substring(72, 8), 2).ToString("X").PadLeft(2, '0') + " " +
                       Convert.ToInt32(strbit.Substring(48, 8), 2).ToString("X").PadLeft(2, '0') + " " + Convert.ToInt32(strbit.Substring(56, 8), 2).ToString("X").PadLeft(2, '0') + " " +
                      Convert.ToInt32(strbit.Substring(32, 8), 2).ToString("X").PadLeft(2, '0') + " " + Convert.ToInt32(strbit.Substring(40, 8), 2).ToString("X").PadLeft(2, '0') + " " +
                      Convert.ToInt32(strbit.Substring(16, 8), 2).ToString("X").PadLeft(2, '0') + " " + Convert.ToInt32(strbit.Substring(24, 8), 2).ToString("X").PadLeft(2, '0') + " " +
                      Convert.ToInt32(strbit.Substring(0, 8), 2).ToString("X").PadLeft(2, '0') + " " + Convert.ToInt32(strbit.Substring(8, 8), 2).ToString("X").PadLeft(2, '0');

                string addhex = (add - 1).ToString("X").PadLeft(4, '0');
                string numhex = count.ToString("X").PadLeft(4, '0');
                string bytecount = (2 * count).ToString("X").PadLeft(2, '0');
                strcmd = "01 10 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " " + bytecount + " " + strcmd;
                byte[] data = ToBytesSendDate(strcmd);
                byte[] crc = Crc18(data);
                strcmd += " " + crc[1].ToString("X").PadLeft(2, '0') + " " + crc[0].ToString("X").PadLeft(2, '0');
                cmd = strcmd;
                cmdlist.Add(strcmd);
                //Thread.Sleep(200);
                Wait(300);
                bool result = GetSendSuccess(devid, add, count);
                return result;
            }
            catch (Exception ex)
            {
                logPrint.Log("命令解析异常");
                return false;
            }
        }
        #endregion

        #region 单个点位
        public bool SingleFloor(int devid, int add, int count, int value)
        {
            try
            {
                string addhex = (add - 1).ToString("X").PadLeft(4, '0');
                string numhex = count.ToString("X").PadLeft(4, '0');
                string bytenum = (2 * count).ToString("X").PadLeft(2, '0');
                string cmd = "0000000" + value.ToString();
                string strvalue = string.Format("{0:X}", Convert.ToInt32(cmd.Substring(0, 8), 2)).PadLeft(2, '0');
                string strcmd = "01 10 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " " + bytenum + " 00" + " " + strvalue;
                byte[] data = ToBytesSendDate(strcmd);
                byte[] crc = Crc18(data);
                strcmd += " " + crc[1].ToString("X").PadLeft(2, '0') + " " + crc[0].ToString("X").PadLeft(2, '0');

                cmdlist.Add(strcmd);
                //Thread.Sleep(200);
                return GetSendSuccess(devid, add, count);
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region 和校验
        public string CheckSum(string data)
        {
            int sum = data.Split(' ').Select(i => Convert.ToInt32(i, 16)).Sum();
            int mod = sum % 256;
            int crc = 0xFF - mod + 1;
            if (crc == 256)
            {
                return "00";
            }
            return crc.ToString("X");
        }
        #endregion

        #region 根据字符串获取物理楼层信息

        public List<int> ToPhyFloor(string floor)
        {
            List<int> list = new List<int>();
            char[] myChar = floor.ToCharArray();
            for (int i = 0; i < myChar.Length; i++)
            {
                if (myChar[i].ToString() == "1")
                {
                    list.Add(phy_list[i]);
                }
            }

            return list;
        }

        #endregion

        #region 根据实际楼层获取物理楼层信息

        public List<int> ToPhyFloorByact(int act_floor)
        {
            List<int> list = new List<int>();
            for (int i = 0; i < act_list.Count; i++)
            {
                if (act_list[i] == act_floor)
                {
                    list.Add(phy_list[i]);
                }
            }
            return list;
        }

        #endregion

        #region 根据物理楼层获取实际楼层信息
        public List<int> ToActFloorByPhy(int phy_floor)
        {
            List<int> list = new List<int>();
            for (int i = 0; i < phy_list.Count; i++)
            {
                if (phy_list[i] == phy_floor)
                {
                    list.Add(act_list[i]);
                }
            }
            return list;
        }

        #endregion

        #region 根据显示楼层获取楼层信息
        public List<int> GetPhyFloorByDisplay(string displayfloor)
        {
            List<int> list = new List<int>();
            for (int i = 0; i < show_list.Count; i++)
            {
                if (show_list[i] == displayfloor)
                {
                    list.Add(phy_list[i]);
                }
            }
            return list;
        }
        #endregion

        #region 更新can、glink、clink、packet
        public bool UpdatePacketStatus(int value)
        {
            string strSql = "UPDATE devinfo SET packet=" + value;
            CommFN<DevInfo> fn = new CommFN<DevInfo>();
            return fn.ExecFN(strSql);
        }

        #endregion

        #region 根据uuid或者卡号获取凭证信息
        public VoucherInfo GetVoucherInfo(VoucherInfo voucher)
        {
            string strSql = "SELECT * FROM cardinfo WHERE UUID='" + voucher.UUID + "' LIMIT 0,1";

            CommFN<VoucherInfo> fn = new CommFN<VoucherInfo>();
            return fn.GetData(strSql);
        }
        #endregion

        #region 进入、退出梯控

        //进入梯控
        public bool LadderControl(int devid)
        {
            lock (locker)
            {
                if (sign_can == 1)
                {
                    return ExceLadder(devid, 0);
                }
                else
                {
                    if (linkstatus == true && _off == 1 && TcpAuthorize == true && mb_status == true)
                    {
                        if (ExceLadder(devid, 0))
                        {
                            sign_kt = -1;
                            return true;
                        }
                    }
                    else
                    {
                        sign_kt = 1;
                    }
                    return true;
                }
            }
        }

        public bool TkControl(int devid)
        {
            lock (locker)
            {
                if (sign_can == 1)
                {
                    return ExceLadder(devid, 0);
                }
                else
                {
                    if (linkstatus == true && _off == 1 && mb_status == true)
                    {
                        if (ExceLadder(devid, 0))
                        {
                            hd_kt = -1;
                            return true;
                        }
                    }
                    else
                    {
                        hd_kt = 1;
                    }
                    return true;
                }
            }
        }

        //退出梯控
        public bool ExitLadderControl(int devid)
        {
            lock (locker)
            {
                return ExceLadder(devid, 1);
            }
        }

        public bool ExceLadder(int devid, int value)
        {
            bool sendresult = SingleFloor(devid, 652, 1, value);
            if (sendresult)
            {
                Elevatormode = value;
                //电梯状态上报
                Report(devid);

                return true;
            }
            else
            {
                return false;
            }
        }

        //金茂切换梯控
        public bool HDTK(int value, string type)
        {
            if (value == 0)
            {
                if (linkstatus == true && _off == 1 && mb_status == true)
                {
                    if (TkControl(0))//授权
                    {
                        ModeRecord modeRecord = new ModeRecord();
                        modeRecord.workmode = value;
                        modeRecord.reason = type;
                        modeRecord.updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        InsertModeRecord(modeRecord);
                        return true;
                    }
                }
                else
                {
                    hd_kt = 1;
                }
            }
            else
            {
                if (ExitLadderControl(1))//退出梯控
                {
                    ModeRecord modeRecord = new ModeRecord();
                    modeRecord.workmode = value;
                    modeRecord.reason = type;
                    modeRecord.updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    InsertModeRecord(modeRecord);
                    return true;
                }
            }


            return false;
        }

        public bool UpdateHdStatus(int value)
        {
            try
            {
                if (UpdateModeStatus(value))
                {
                    if (value == 0)
                    {
                        TcpAuthorize = true;
                    }
                    else if (value == 1)
                    {
                        TcpAuthorize = false;
                    }
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        public bool UpdateLightMode(int value)
        {
            try
            {
                if (UpdateLight(value))
                {
                    light = value;
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        #region 更新点亮模式
        public bool UpdateLight(int mode)
        {
            string strSql = "UPDATE devinfo SET lightmode=" + mode;
            CommFN<DevInfo> fn = new CommFN<DevInfo>();
            return fn.ExecFN(strSql);
        }
        #endregion


        public void Report(int devid)
        {
            ElevatorPoint point = new ElevatorPoint();
            memoryCache.TryGetValue(devid, out point);

            Device elevator = new Device();
            if (point.falut == 1)
            {
                elevator.State = 2;
            }
            else
            {
                elevator.State = 1;
            }

            elevator.Floor = point.physicalfloor;

            if (point.up == 1)
            {
                elevator.Dicrection = 1;
            }
            else if (point.down == 1)
            {
                elevator.Dicrection = 2;
            }
            else
            {
                elevator.Dicrection = 0;
            }

            devState.ElevatorDevReport(elevator);
        }


        #endregion

        #region 参数设置
        public bool SetParameter(int devid, string type, List<FloorAddress> list, string value)
        {
            int analysistype;
            int datacount = 0;
            int address;
            switch (type)
            {
                case "前门CRS":
                    address = 101;
                    analysistype = 1;
                    datacount = 40;
                    break;
                case "后门CRS":
                    address = 141;
                    analysistype = 1;
                    datacount = 40;
                    break;
                case "前门CB":
                    address = 181;
                    analysistype = 1;
                    datacount = 40;
                    break;
                case "后门CB":
                    address = 221;
                    analysistype = 1;
                    datacount = 40;
                    break;
                case "前门UHB":
                    address = 261;
                    analysistype = 1;
                    datacount = 40;
                    break;
                case "前门DHB":
                    address = 301;
                    analysistype = 1;
                    datacount = 40;
                    break;
                case "后门UHB":
                    address = 341;
                    analysistype = 1;
                    datacount = 40;
                    break;
                case "后门DHB":
                    address = 381;
                    analysistype = 1;
                    datacount = 40;
                    break;
                case "显示楼层":
                    address = 421;
                    analysistype = 2;
                    datacount = 80;
                    break;
                /*case "ST1[911]":
                    address = 501;
                    analysistype = 3;
                    datacount = 1;
                    break;
                case "ST2[912]":
                    address = 502;
                    analysistype = 3;
                    datacount = 1;
                    break;
                case "ST3[913]":
                    address = 503;
                    analysistype = 3;
                    datacount = 1;
                    break;
                case "RST1[914]":
                    address = 504;
                    analysistype = 3;
                    datacount = 1;
                    break;
                case "RST2[915]":
                    address = 505;
                    analysistype = 3;
                    datacount = 1;
                    break;
                case "RST3[916]":
                    address = 506;
                    analysistype = 3;
                    datacount = 1;
                    break;
                case "CUDL[20]":
                    address = 507;
                    analysistype = 3;
                    datacount = 1;
                    break;
                case "CDDL[21]":
                    address = 508;
                    analysistype = 3;
                    datacount = 1;
                    break;
                case "OOL[737]":
                    address = 509;
                    analysistype = 3;
                    datacount = 1;
                    break;
                case "INS[602]":
                    address = 510;
                    analysistype = 3;
                    datacount = 1;
                    break;
                case "EFL[716]":
                    address = 511;
                    analysistype = 3;
                    datacount = 1;
                    break;
                case "DHB[620]":
                    address = 512;
                    analysistype = 3;
                    datacount = 1;
                    break;
                case "CRC[639]":
                    address = 513;
                    analysistype = 3;
                    datacount = 1;
                    break;
                case "DOOR":
                    address = 514;
                    analysistype = 4;
                    datacount = 1;
                    break;
                case "IC":
                    address = 515;
                    analysistype = 4;
                    datacount = 1;
                    break;
                case "VISITOR":
                    address = 516;
                    analysistype = 4;
                    datacount = 1;
                    break;
                case "CAN":
                    address = 517;
                    analysistype = 5;
                    datacount = 1;
                    break;*/
                default:
                    address = 0;
                    analysistype = 0;
                    break;
            }
            string replay = analysis(devid, address, analysistype, list, value);
            if (SendMsg(replay))
            {
                //Thread.Sleep(500);
                if (GetSendSuccess(devid, address, datacount))
                {
                    return true;
                }
            }
            return false;
        }

        public string analysis(int devid, int add_start, int type, List<FloorAddress> list, string value)
        {
            string strCmd = string.Empty;
            if (type == 1)
            {
                strCmd = AddSetDouble(devid, add_start, list);
            }
            else if (type == 2)
            {
                strCmd = AddSetFloor(devid, add_start, list);
            }
            else if (type == 3)
            {
                strCmd = AddSetPointSingle(devid, add_start, value);
            }
            else if (type == 4)
            {
                strCmd = AddSetPointDouble(devid, add_start, value);
            }
            else if (type == 4)
            {
                strCmd = AddSetPoint(devid, add_start, value);
            }
            return strCmd;
        }

        public string AddSetDouble(int devid, int add_start, List<FloorAddress> list)
        {
            string strcmd = string.Empty;
            for (int i = 1; i <= 80; i++)
            {
                foreach (var item in list)
                {
                    if (item.ID == i)
                    {
                        if (!string.IsNullOrEmpty(item.address))
                        {
                            string[] arr = item.address.Split(',');
                            string strhex = Convert.ToString(Convert.ToInt32(arr[0]), 2).PadLeft(6, '0') + Convert.ToString(Convert.ToInt32(arr[1]), 2).PadLeft(2, '0');
                            strcmd += string.Format("{0:X}", Convert.ToInt32(strhex, 2)).PadLeft(2, '0') + " ";
                        }
                        else
                        {
                            strcmd += "00 ";
                        }
                        break;
                    }
                }
            }

            int count = 40;
            string addhex = (add_start - 1).ToString("X").PadLeft(4, '0');
            string numhex = count.ToString("X").PadLeft(4, '0');
            string bytecount = (2 * count).ToString("X").PadLeft(2, '0');
            //strcmd = devid.ToString("X").PadLeft(2, '0') + " 10 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " " + bytecount + " " + strcmd;
            strcmd = "01 10 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " " + bytecount + " " + strcmd;
            strcmd.TrimEnd(' ');
            byte[] data = ToBytesSendDate(strcmd);
            byte[] crc = Crc18(data);
            strcmd += crc[1].ToString("X").PadLeft(2, '0') + " " + crc[0].ToString("X").PadLeft(2, '0');

            return strcmd;
        }

        public string AddSetFloor(int devid, int add_start, List<FloorAddress> list)
        {
            string strcmd = string.Empty;
            for (int i = 1; i <= 80; i++)
            {
                string value = string.Empty;
                FloorAddress floorAddress = list.FirstOrDefault(t => t.ID == i);

                if (floorAddress != null)
                {
                    if (!string.IsNullOrEmpty(floorAddress.address))
                    {
                        strcmd += StringToHex(floorAddress.address.PadLeft(2, '0'));
                    }
                    else
                    {
                        strcmd += "00 00 ";
                    }
                }
                else
                {
                    strcmd += "00 00 ";
                }


                /* foreach (var item in list)
                 {
                     if (item.ID == i)
                     {
                         if (!string.IsNullOrEmpty(value))
                         {
                             strcmd += StringToHex(value.PadLeft(2, '0'));
                         }
                         else
                         {
                             strcmd += "00 00 ";
                         }
                         break;
                     }
                 }*/
            }
            strcmd.TrimEnd(' ');
            int count = 80;
            string addhex = (add_start - 1).ToString("X").PadLeft(4, '0');
            string numhex = count.ToString("X").PadLeft(4, '0');
            string bytecount = (2 * count).ToString("X").PadLeft(2, '0');
            //strcmd = devid.ToString("X").PadLeft(2, '0') + " 10 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " " + bytecount + " " + strcmd;
            strcmd = "01 10 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " " + bytecount + " " + strcmd;
            byte[] data = ToBytesSendDate(strcmd);
            byte[] crc = Crc18(data);
            strcmd += crc[1].ToString("X").PadLeft(2, '0') + " " + crc[0].ToString("X").PadLeft(2, '0');

            return strcmd;
        }

        public string AddSetPointSingle(int devid, int add_start, string value)
        {
            string strcmd = string.Empty;

            string[] arr = value.Split(',');
            string strhex = Convert.ToString(Convert.ToInt32(arr[0]), 2).PadLeft(6, '0') + Convert.ToString(Convert.ToInt32(arr[1]), 2).PadLeft(2, '0');
            strcmd += "00 " + string.Format("{0:X}", System.Convert.ToInt32(strhex, 2)).PadLeft(2, '0') + " ";

            strcmd.TrimEnd(' ');
            int count = 1;
            string addhex = (add_start - 1).ToString("X").PadLeft(4, '0');
            string numhex = count.ToString("X").PadLeft(4, '0');
            string bytecount = (2 * count).ToString("X").PadLeft(2, '0');
            //strcmd = devid.ToString("X").PadLeft(2, '0') + " 10 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " " + bytecount + " " + strcmd;
            strcmd = "01 10 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " " + bytecount + " " + strcmd;
            byte[] data = ToBytesSendDate(strcmd);
            byte[] crc = Crc18(data);
            strcmd += crc[1].ToString("X").PadLeft(2, '0') + " " + crc[0].ToString("X").PadLeft(2, '0');

            return strcmd;
        }

        public string AddSetPointDouble(int devid, int add_start, string value)
        {
            string strcmd = string.Empty;

            string strhex = Convert.ToString(Convert.ToInt32(value), 2).PadLeft(4, '0');
            strcmd += strhex.Substring(0, 2) + " " + strhex.Substring(2, 2);

            int count = 1;
            string addhex = (add_start - 1).ToString("X").PadLeft(4, '0');
            string numhex = count.ToString("X").PadLeft(4, '0');
            string bytecount = (2 * count).ToString("X").PadLeft(2, '0');
            //strcmd = devid.ToString("X").PadLeft(2, '0') + " 10 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " " + bytecount + " " + strcmd;
            strcmd = "01 10 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " " + bytecount + " " + strcmd;
            byte[] data = ToBytesSendDate(strcmd);
            byte[] crc = Crc18(data);
            strcmd += " " + crc[1].ToString("X").PadLeft(2, '0') + " " + crc[0].ToString("X").PadLeft(2, '0');

            return strcmd;
        }

        public string AddSetPoint(int devid, int add_start, string value)
        {
            string strcmd = string.Empty;

            string strhex = "0000000" + value;
            strcmd += strhex.Substring(0, 2) + " " + strhex.Substring(2, 2);

            int count = 1;
            string addhex = (add_start - 1).ToString("X").PadLeft(4, '0');
            string numhex = count.ToString("X").PadLeft(4, '0');
            string bytecount = (2 * count).ToString("X").PadLeft(2, '0');
            //strcmd = devid.ToString("X").PadLeft(2, '0') + " 10 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " " + bytecount + " " + strcmd;
            strcmd = "01 10 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " " + bytecount + " " + strcmd;
            byte[] data = ToBytesSendDate(strcmd);
            byte[] crc = Crc18(data);
            strcmd += " " + crc[1].ToString("X").PadLeft(2, '0') + " " + crc[0].ToString("X").PadLeft(2, '0');

            return strcmd;
        }

        public string StringToHex(string strEncode)
        {
            string strReturn = "";
            foreach (short shortx in strEncode.ToCharArray())
            {
                if (shortx < 0)
                {
                    strReturn += "30" + " ";
                }
                else
                {
                    strReturn += shortx.ToString("X2") + " ";
                }

            }
            //strReturn = strReturn.TrimEnd(' ');
            return strReturn;
        }

        public List<FloorAddress> ReadParameter(int devid, string type)
        {
            List<FloorAddress> list = new List<FloorAddress>();
            try
            {
                int datacount = 0;
                int address;
                int analysistype;
                switch (type)
                {
                    case "前门CRS":
                        address = 101;
                        analysistype = 1;
                        datacount = 40;
                        break;
                    case "后门CRS":
                        address = 141;
                        analysistype = 1;
                        datacount = 40;
                        break;
                    case "前门CB":
                        address = 181;
                        analysistype = 1;
                        datacount = 40;
                        break;
                    case "后门CB":
                        address = 221;
                        analysistype = 1;
                        datacount = 40;
                        break;
                    case "前门UHB":
                        address = 261;
                        analysistype = 1;
                        datacount = 40;
                        break;
                    case "前门DHB":
                        address = 301;
                        analysistype = 1;
                        break;
                    case "后门UHB":
                        address = 341;
                        analysistype = 1;
                        datacount = 40;
                        break;
                    case "后门DHB":
                        address = 381;
                        analysistype = 1;
                        datacount = 40;
                        break;
                    case "显示楼层":
                        address = 421;
                        analysistype = 2;
                        datacount = 80;
                        break;
                    /*case "ST1[911]":
                        address = 501;
                        analysistype = 3;
                        datacount = 1;
                        break;
                    case "ST2[912]":
                        address = 502;
                        analysistype = 3;
                        datacount = 1;
                        break;
                    case "ST3[913]":
                        address = 503;
                        analysistype = 3;
                        datacount = 1;
                        break;
                    case "RST1[914]":
                        address = 504;
                        analysistype = 3;
                        datacount = 1;
                        break;
                    case "RST2[915]":
                        address = 505;
                        analysistype = 3;
                        datacount = 1;
                        break;
                    case "RST3[916]":
                        address = 506;
                        analysistype = 3;
                        datacount = 1;
                        break;
                    case "CUDL[20]":
                        address = 507;
                        analysistype = 3;
                        datacount = 1;
                        break;
                    case "CDDL[21]":
                        address = 508;
                        analysistype = 3;
                        datacount = 1;
                        break;
                    case "OOL[737]":
                        address = 509;
                        analysistype = 3;
                        datacount = 1;
                        break;
                    case "INS[602]":
                        address = 510;
                        analysistype = 3;
                        datacount = 1;
                        break;
                    case "EFL[716]":
                        address = 511;
                        analysistype = 3;
                        datacount = 1;
                        break;
                    case "DHB[620]":
                        address = 512;
                        analysistype = 3;
                        datacount = 1;
                        break;
                    case "CRC[639]":
                        address = 513;
                        analysistype = 3;
                        datacount = 1;
                        break;
                    case "DOOR":
                        address = 514;
                        analysistype = 4;
                        datacount = 1;
                        break;
                    case "IC":
                        address = 515;
                        analysistype = 4;
                        datacount = 1;
                        break;
                    case "VISITOR":
                        address = 516;
                        analysistype = 4;
                        datacount = 1;
                        break;
                    case "CAN":
                        address = 517;
                        analysistype = 5;
                        datacount = 1;
                        break;*/
                    default:
                        address = 0;
                        analysistype = 0;
                        datacount = 0;
                        break;
                }
                list = GetType(devid, address, analysistype, datacount);

                return list;
            }
            catch (Exception ex)
            {
                logPrint.Log(ex.ToString());
                return list;
            }
        }

        public List<FloorAddress> GetType(int devid, int add_start, int type, int datacount)
        {
            List<FloorAddress> list = new List<FloorAddress>();
            try
            {
                string addhex = (add_start - 1).ToString("X").PadLeft(4, '0');
                string numhex = datacount.ToString("X").PadLeft(4, '0');
                //string strCmd = devid.ToString("X").PadLeft(2, '0') + " 03 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " ";
                string strCmd = "01 03 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " ";
                byte[] data = ToBytesSendDate(strCmd);
                byte[] crc = Crc18(data);
                strCmd += crc[1].ToString("X").PadLeft(2, '0') + " " + crc[0].ToString("X").PadLeft(2, '0');

                cmdlist.Add(strCmd);

                //Thread.Sleep(500);

                byte[] buffer = GetAddSetparameterData(devid, datacount * 2);

                if (buffer != null)
                {
                    if (type == 1)
                    {
                        list = ReadAddDouble(buffer);
                    }
                    else if (type == 2)
                    {
                        list = ReadAddFloor(buffer);
                    }
                    else if (type == 3)
                    {
                        list = ReadAddPointSingle(buffer);
                    }
                    else if (type == 4)
                    {
                        list = ReadAddPointDouble(buffer);
                    }
                    else if (type == 5)
                    {
                        list = ReadAddPoint(buffer);
                    }
                }

                return list;
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.ToString());
                return list;
            }
        }

        public List<FloorAddress> ReadAddDouble(byte[] buffer)
        {
            List<FloorAddress> list = new List<FloorAddress>();
            for (int i = 1; i <= 80; i++)
            {
                FloorAddress floorAddress = new FloorAddress();
                string value = Convert.ToString(buffer[i + 2], 2).PadLeft(8, '0');
                string address = string.Format("{0},{1}", Convert.ToInt32(value.Substring(0, 6), 2), Convert.ToInt32(value.Substring(6, 2), 2));
                floorAddress.ID = i;
                floorAddress.address = address;
                list.Add(floorAddress);
            }
            return list;
        }

        public List<FloorAddress> ReadAddFloor(byte[] buffer)
        {
            List<FloorAddress> list = new List<FloorAddress>();
            byte[] key = new byte[2];
            for (int i = 1; i <= 80; i++)
            {
                key[0] = buffer[2 * (i + 1) - 1];
                key[1] = buffer[2 * (i + 1)];
                string value = HexToString(key);
                FloorAddress floorAddress = new FloorAddress();
                floorAddress.ID = i;
                floorAddress.address = value;
                list.Add(floorAddress);
            }
            return list;
        }
        public List<FloorAddress> ReadAddPointSingle(byte[] buffer)
        {
            List<FloorAddress> list = new List<FloorAddress>();
            FloorAddress floorAddress = new FloorAddress();
            floorAddress.ID = 1;
            floorAddress.address = buffer[4].ToString();
            list.Add(floorAddress);
            return list;
        }

        public List<FloorAddress> ReadAddPointDouble(byte[] buffer)
        {
            List<FloorAddress> list = new List<FloorAddress>();
            FloorAddress floorAddress = new FloorAddress();
            string value = Convert.ToString(buffer[4], 2).PadLeft(8, '0');
            string address = string.Format("{0},{1}", Convert.ToInt32(value.Substring(0, 6), 2), Convert.ToInt32(value.Substring(6, 2), 2));
            floorAddress.ID = 1;
            floorAddress.address = address;
            list.Add(floorAddress);
            return list;
        }
        public List<FloorAddress> ReadAddPoint(byte[] buffer)
        {
            List<FloorAddress> list = new List<FloorAddress>();
            FloorAddress floorAddress = new FloorAddress();
            string value = Convert.ToString(buffer[4], 2).PadLeft(8, '0');
            floorAddress.ID = 1;
            floorAddress.address = value.Substring(7, 1);
            list.Add(floorAddress);
            return list;
        }

        //获取参数数据
        public byte[] GetAddSetparameterData(int devid, int datacount)
        {
            int count = 0;
            while (true)
            {
                try
                {
                    byte[] buffer = byteSerialPortRecv;
                    byte[] crcdata = GetAddparameterData(buffer, devid, datacount);
                    if (crcdata != null)
                    {
                        return crcdata;
                    }
                    else
                    {
                        return null;
                    }
                    /* if (count > 2)
                     {
                         return null;
                     }
                     count++;
                     //Thread.Sleep(1000);*/
                }
                catch
                {
                    continue;
                }
            }
        }

        public byte[] GetAddparameterData(byte[] buffer, int devid, int datacount)
        {
            devid = 1;
            byte[] data = GetAddSetparameterData(buffer, devid, datacount);
            if (data != null)
            {
                int length = data.Length;
                byte[] crcdata = new byte[length - 2];
                for (int i = 0; i < length - 2; i++)
                {
                    crcdata[i] = data[i];
                }
                byte[] crc = Crc18(crcdata);
                if (crc[0] == data[length - 1] && crc[1] == data[length - 2])
                {
                    return data;
                }
            }
            return null;
        }

        public byte[] GetAddSetparameterData(byte[] buffer, int devid, int datacount)
        {
            for (int i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] == devid && buffer[i + 1] == 3 && buffer[i + 2] == datacount)
                {
                    string a = buffer[i + 2].ToString("X2").PadLeft(2, '0');
                    int num = int.Parse(a, System.Globalization.NumberStyles.HexNumber);
                    byte[] data = new byte[num + 5];
                    int n = 0;
                    for (int j = i; j < i + num + 5; j++)
                    {
                        data[n] = buffer[j];
                        n++;
                    }
                    Array.Clear(byteSerialPortRecv, i, data.Length);

                    return data;
                }
            }
            return null;
        }

        #endregion

        #region 十六进制转string
        public string HexToString(byte[] buffer)
        {
            // 将 byte数组 解码成 字符串：
            string getData = Encoding.Default.GetString(buffer);
            return getData;
        }
        #endregion

        #region RS232下发成功回复
        public bool GetSendSuccess(int devid, int addressid, int datacount)
        {
            lock (replaylocker)
            {
                try
                {
                    int i = 0;
                    while (i < 3)
                    {
                        byte[] buffer = byteSerialPortRecv;
                        devid = 1;
                        if (GetSuccessData(buffer, devid, addressid, datacount))
                        {
                            return true;
                        }
                        i++;
                        //Thread.Sleep(200);
                    }
                    logPrint.Log("未收到电梯回复消息");
                    return false;
                }
                catch (Exception ex)
                {
                    logPrint.Log("接受电梯回复消息异常");
                    return false;
                }
            }
        }

        public bool GetSuccessData(byte[] buffer, int devid, int addressid, int datacount)
        {
            string add = (addressid - 1).ToString("X").PadLeft(4, '0');
            string count = datacount.ToString("X").PadLeft(4, '0');
            int add_h = Convert.ToInt32(add.Substring(0, 2), 16);
            int add_l = Convert.ToInt32(add.Substring(2, 2), 16);
            int count_h = Convert.ToInt32(count.Substring(0, 2), 16);
            int count_l = Convert.ToInt32(count.Substring(2, 2), 16);
            for (int i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] == devid && buffer[i + 1] == 0x10 && buffer[i + 2] == add_h && buffer[i + 3] == add_l && buffer[i + 4] == count_h && buffer[i + 5] == count_l)
                {
                    byte[] bu = new byte[8];
                    for (int k = 0; k < 8; k++)
                    {
                        bu[k] = byteSerialPortRecv[i + k];
                    }
                    Array.Clear(byteSerialPortRecv, i, 8);

                    return true;
                }
            }
            return false;
        }
        #endregion

        #region RS232下发成功回复
        public bool GetSendttyS0Success(int devid, int addressid, int datacount)
        {
            lock (replaylocker)
            {
                try
                {
                    int i = 0;
                    while (i < 3)
                    {
                        devid = 1;
                        if (GetSuccessttyS0Data(devid, addressid, datacount))
                        {
                            return true;
                        }
                        i++;
                        Wait(200);
                    }
                    logPrint.Log("未收到电梯回复消息");
                    return false;
                }
                catch (Exception ex)
                {
                    logPrint.Log("接受电梯回复消息异常");
                    return false;
                }
            }
        }

        /*  public bool GetSuccessttyS0Data(byte[] buffer, int devid, int addressid, int datacount)
          {
              string add = (addressid - 1).ToString("X").PadLeft(4, '0');
              string count = datacount.ToString("X").PadLeft(4, '0');
              int add_h = Convert.ToInt32(add.Substring(0, 2), 16);
              int add_l = Convert.ToInt32(add.Substring(2, 2), 16);
              int count_h = Convert.ToInt32(count.Substring(0, 2), 16);
              int count_l = Convert.ToInt32(count.Substring(2, 2), 16);
              for (int i = 0; i < buffer.Length; i++)
              {
                  if (buffer[i] == devid && buffer[i + 1] == 0x10 && buffer[i + 2] == add_h && buffer[i + 3] == add_l && buffer[i + 4] == count_h && buffer[i + 5] == count_l)
                  {
                      byte[] bu = new byte[8];
                      for (int k = 0; k < 8; k++)
                      {
                          bu[k] = byteSerialPortRecv485_1[i + k];
                      }
                      Array.Clear(byteSerialPortRecv485_1, i, 8);

                      return true;
                  }
              }
              return false;
          }*/

        public bool GetSuccessttyS0Data(int devid, int addressid, int datacount)
        {
            string add = (addressid - 1).ToString("X").PadLeft(4, '0');
            string count = datacount.ToString("X").PadLeft(4, '0');
            int add_h = Convert.ToInt32(add.Substring(0, 2), 16);
            int add_l = Convert.ToInt32(add.Substring(2, 2), 16);
            int count_h = Convert.ToInt32(count.Substring(0, 2), 16);
            int count_l = Convert.ToInt32(count.Substring(2, 2), 16);
            for (int i = 0; i < TmpDataReceived.Count; i++)
            {
                if (TmpDataReceived[i] == devid && TmpDataReceived[i + 1] == 0x10 && TmpDataReceived[i + 2] == add_h && TmpDataReceived[i + 3] == add_l && TmpDataReceived[i + 4] == count_h && TmpDataReceived[i + 5] == count_l)
                {
                    TmpDataReceived.RemoveRange(i, i + 8);

                    return true;
                }
            }
            return false;
        }

        public string ByteArrayToHexs(byte[] data)
        {
            if (data.Length <= 0) return "";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i].ToString("X2"));
            }
            string str = sb.ToString();
            return str;
        }
        #endregion

        #region 检查七合一面板连接状态
        public void CheckDevConnect()
        {
            Task task = new Task(async () =>
            {
                while (true)
                {
                    try
                    {
                        if (token.IsCancellationRequested)
                        {
                            return;
                        }
                        resetEvent.WaitOne();
                        //do something
                        CheckRS485Status(deviceid);
                        await Task.Delay(5000);
                    }
                    catch
                    {
                        continue;
                    }
                }
            }, token);
            task.Start();
        }

        public void CheckRS485Status(int devid)
        {
            DateTime now = DateTime.Now;
            TimeSpan ts = now.Subtract(sendtime);
            int sec = (int)ts.TotalSeconds;
            if (TcpAuthorize)
            {
                if (sendtime.Year != 1)
                {
                    if (Elevatormode == 0 && sec > 180) //授权模式下，超过180秒未收到心跳
                    {
                        mb_status = false;

                        logPrint.Log("超过3分钟未收到心跳，切换为普通模式");
                        ExitLadderControl(devid);
                        sign_kt = -1;
                        ModeRecord mode = new ModeRecord();
                        mode.workmode = 1;
                        mode.updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        mode.reason = "超过3分钟未收到心跳，切换为普通模式";
                        InsertModeRecord(mode);

                        Equipment equipment = new Equipment();
                        equipment.devtype = "七合一面板";
                        equipment.state = 1;
                        equipment.actiontime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        equipment.reason = "超过3分钟未收到心跳";
                        InsertEquipment(equipment);
                    }
                    else if (Elevatormode == 0 && sec <= 180)//授权模式下，收到心跳
                    {
                        if (mb_status == false)
                        {
                            Equipment equipment = new Equipment();
                            equipment.devtype = "七合一面板";
                            equipment.state = 0;
                            equipment.actiontime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            equipment.reason = "收到心跳";
                            InsertEquipment(equipment);
                        }

                        mb_status = true;
                    }
                }
            }

            if (hd_kt == 1)
            {
                //logPrint.Log("金茂平台有未发送的进入梯控");
                HDTK(0, "");
            }

            if (sign_kt == 1)
            {
                LadderControl(0);
            }

        }
        #endregion

        #region 检查rs232连接状态
        public void Check232Connect()
        {
            try
            {
                issend = true;
                sendtimer = new Timer(200);//实例化Timer类，设置间隔时间为200毫秒；

                sendtimer.Elapsed += new ElapsedEventHandler(Check232Status);//到达时间的时候执行事件；

                sendtimer.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；

                sendtimer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件；
            }
            catch (Exception ex)
            {
            }
        }

        public void Check232Status(object source, ElapsedEventArgs e)
        {
            if (issend)
            {
                issend = false;
                try
                {
                    string cmd = "01 03 00 00 00 06 C5 C8";
                    if (cmdlist.Count == 0)
                    {
                        if (SendMsg(cmd))
                        {
                            bool result = GetBasicData(deviceid);
                            if (result)
                            {
                                if (status_232 == false)
                                {
                                    count_232 = 0;
                                    status_232 = true;
                                    Equipment equipment = new Equipment();
                                    equipment.devtype = "电梯控制板";
                                    equipment.reason = "电梯控制板通信成功";
                                    equipment.state = 0;
                                    equipment.actiontime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    InsertEquipment(equipment);
                                }
                            }
                            else
                            {
                                if (status_232 && count_232 > 10)
                                {
                                    logPrint.Log("232连接异常");
                                    status_232 = false;
                                    count_232 = 0;
                                    Equipment equipment = new Equipment();
                                    equipment.devtype = "电梯控制板";
                                    equipment.state = 1;
                                    equipment.actiontime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    equipment.reason = "与电梯断开通信";
                                    InsertEquipment(equipment);
                                }
                                else
                                {
                                    count_232++;
                                }
                            }
                        }
                        issend = true;
                    }
                    else
                    {
                        string sendcmd = cmdlist[0];
                        int sendtime = 0;
                        while (sendtime < 3)
                        {
                            if (SendMsg(sendcmd))
                            {
                                issend = true;
                                cmdlist.RemoveAt(0);
                                break;
                            }
                            else
                            {
                                sendtime++;
                                //Thread.Sleep(200);
                            }
                        }
                        issend = true;
                        cmdlist.RemoveAt(0);
                    }
                }
                catch (Exception ex)
                {
                }
            }
            else
            {
                return;
            }
        }
        #endregion

        public void QueryMode()
        {
            DevInfo dev = GetDevInfo();
            if (dev != null)
            {
                Elevatormode = dev.workmode;
            }
            if (Elevatormode == 0)
            {
                TcpAuthorize = true;
            }
            else if (Elevatormode == 1)
            {
                TcpAuthorize = false;
            }
        }

        public DevInfo GetDevInfo()
        {
            string strSql = "SELECT * FROM devinfo LIMIT 0,1";
            CommFN<DevInfo> fn = new CommFN<DevInfo>();
            return fn.GetData(strSql);
        }

        #region 查询所有楼层信息
        public List<FloorInfo> GetAllFloor()
        {
            string strSql = "SELECT * FROM floor ORDER by actualfloor ASC";
            CommFN<FloorInfo> fn = new CommFN<FloorInfo>();
            return fn.GetDataList(strSql);
        }
        #endregion

        #region 更新数据库工作状态
        public bool UpdateModeStatus(int mode)
        {
            string strSql = "UPDATE devinfo SET workmode=" + mode;
            CommFN<DevInfo> fn = new CommFN<DevInfo>();
            return fn.ExecFN(strSql);
        }
        #endregion

        /* /// <summary>
         /// 建立主梯TcpServer
         /// </summary>
         public bool BuildTcpServer(string ip, int port)
         {
             try
             {
                 //定义一个套接字用于监听客户端发来的信息 包含3个参数(IP4寻址协议,流式连接,TCP协议)
                 socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                 //服务端发送信息 需要1个IP地址和端口号
                 //IPAddress ipaddress = IPAddress.Parse("172.16.1.159");
                 IPAddress ipaddress = IPAddress.Parse(ip);  //获取文本框输入的IP地址
                 IPEndPoint endpoint = new IPEndPoint(ipaddress, port); //监听绑定的网络节点

                 socketWatch.Bind(endpoint);
                 //将套接字的监听队列长度限制为20
                 socketWatch.Listen(20);
                 //创建一个监听委托
                 ThreadStart ts = new ThreadStart(WatchConnecting);
                 //创建一个监听线程 
                 threadWatch = new Thread(ts);
                 //将窗体线程设置为与后台同步
                 threadWatch.IsBackground = true;
                 //启动线程
                 threadWatch.Start();
                 logPrint.Log("服务端启动服务成功!");

                 return true;
             }
             catch (Exception ex)
             {
                 logPrint.Log("服务端启动服务失败!");
                 return false;
             }
         }

         /// <summary>
         /// 监听副梯发来的请求
         /// </summary>
         private void WatchConnecting()
         {
             while (true)  //持续不断监听客户端发来的请求
             {
                 //等待客户端的连接 并且创建一个负责通信的Socket 
                 socConnection = socketWatch.Accept();
                 // 将与客户端连接的 套接字 对象添加到集合中；
                 dict.Add(socConnection.RemoteEndPoint.ToString(), socConnection);
                 //创建一个通信线程 
                 // ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRecMsg);
                 thr = new Thread(ServerRecMsg);
                 thr.IsBackground = true;
                 //启动线程
                 thr.Start(socConnection);
                 // 将新建的线程 添加 到线程的集合中去。
                 dictThread.Add(socConnection.RemoteEndPoint.ToString(), thr);
             }
         }

         /// <summary>
         /// 接收副梯发来的信息 
         /// </summary>
         /// <param name="socketClientPara">客户端套接字对象</param>
         private void ServerRecMsg(object socketClientPara)
         {
             while (true)
             {
                 //创建一个内存缓冲区 其大小为1024*1024字节  即1M
                 byte[] arrServerRecMsg = new byte[1024 * 1024];
                 Socket socketServer = socketClientPara as Socket; //类型转换 objec->Socket
                 try
                 {
                     //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度
                     int length = -1;
                     length = socketServer.Receive(arrServerRecMsg);
                     //将机器接受到的字节数组转换为人可以读懂的字符串
                     if (length > 0)
                     {
                         string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);

                         SlaveStatus = StringToHex(strSRecMsg);
                         slavsendtime = DateTime.Now;
                         MasterSend("01");
                     }
                 }
                 catch (Exception ex)
                 {
                     logPrint.Log("客户端已断开连接！");
                     // 从 通信套接字 集合中删除被中断连接的通信套接字；
                     dict.Remove(socketServer.RemoteEndPoint.ToString());
                     // 从通信线程集合中删除被中断连接的通信线程对象；
                     dictThread.Remove(socketServer.RemoteEndPoint.ToString());

                     break;
                 }
             }
         }*/



        /*/// <summary>
        /// 连接主梯 
        /// </summary>
        public bool ConnectingToServer(string ip, int port)
        {
            try
            {
                clientserver = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientserver.Connect(ip, port);
                clientserver.ReceiveTimeout = 10000;
                clientthread = new Thread(RecMsg);
                clientthread.Start(clientserver);
                logPrint.Log("主梯连接成功");
                UpdateSlaveConnect(true);
                return true;
            }
            catch (Exception ex)
            {
                logPrint.Log("主梯连接异常！");
                UpdateSlaveConnect(false);
                return false;
            }
        }

        /// <summary>
        /// 接收主梯发来信息的方法
        /// </summary>
        private void RecMsg(object obj)
        {
            byte[] buffer = new byte[2048];
            int length = 0;
            while (true) //持续监听服务端发来的消息
            {
                try
                {
                    length = clientserver.Receive(buffer);
                    if (length <= 0)
                    {
                        logPrint.Log("未收到主梯回复");
                        UpdateSlaveConnect(false);
                        break;
                    }
                    else
                    {
                        UpdateSlaveConnect(true);
                    }
                }
                catch (Exception ex)
                {
                    logPrint.Log("主梯回复异常");
                    UpdateSlaveConnect(false);
                    continue;
                }
            }
        }

        /// <summary>
        /// 发送电梯状态到主梯
        /// </summary>
        /// <param name="sendMsg">发送的字符串信息</param>
        public bool ClientSendMsg(byte[] arrClientSendMsg)
        {
            try
            {
                //将输入的内容字符串转换为机器可以识别的字节数组
                //byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
                //Console.WriteLine(arrClientSendMsg);
                //调用客户端套接字发送字节数组
                clientserver.Send(arrClientSendMsg);
                // SlaveConnect = true;
                return true;
            }
            catch (Exception ex)
            {
                //  clientserver.Close();
                return false;
            }
        }*/

        public int SlaveStatusCmd()
        {
            int i = 9999;
            if (statussend.Year == 1)
            {
                return i;
            }
            else
            {
                TimeSpan ts1 = new TimeSpan(DateTime.Now.Ticks);
                TimeSpan ts2 = new TimeSpan(statussend.Ticks);
                TimeSpan ts3 = ts1.Subtract(ts2).Duration();
                i = (int)ts3.TotalMilliseconds;
            }

            return i;
        }

        #region 副梯tcp连接情况

        /// <summary>
        /// 副梯检查tcp连接状态
        /// </summary>
        public void CheckTcpConnect()
        {
            try
            {
                slavetimer = new Timer(2000);//实例化Timer类，设置间隔时间为200毫秒；

                slavetimer.Elapsed += new ElapsedEventHandler(CheckTcpClientStatus);//到达时间的时候执行事件；

                slavetimer.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；

                slavetimer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件；
            }
            catch (Exception ex)
            {
                logPrint.Log("报错信息：" + ex.ToString());
            }
        }

        public void CheckTcpClientStatus(object source, ElapsedEventArgs e)
        {
            lock (tcplocker)
            {
                if (!QuerySlaveStatus())
                {
                    try
                    {
                        if (!ConnectServer(mainIP, mainPort))
                        {
                            //Thread.Sleep(10000);
                        }
                    }
                    catch
                    {
                        logPrint.Log("连接主梯异常");
                        UpdateSlaveConnect(false);
                        //Thread.Sleep(10000);
                    }
                }
            }
        }

        public void UpdateSlaveConnect(bool status)
        {
            lock (statuslocker)
            {
                SlaveConnect = status;
            }
        }

        public bool QuerySlaveStatus()
        {
            return SlaveConnect;
        }

        #endregion

        #region 主梯检查副梯连接情况,4秒检查一次状态，断开情况下10秒连接一次主电梯
        public void CheckSlaveConnect()
        {
            try
            {
                mastertimer = new Timer(4000);//实例化Timer类，设置间隔时间为200毫秒；

                mastertimer.Elapsed += new ElapsedEventHandler(CheckSlaveStatus);//到达时间的时候执行事件；

                mastertimer.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；

                mastertimer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件；
            }
            catch (Exception ex)
            {
                logPrint.Log("报错信息：" + ex.ToString());
                //throw;
            }
        }

        public void CheckSlaveStatus(object source, ElapsedEventArgs e)
        {
            try
            {
                int sj = SlaveConnectTime();
                if (sj > 6000)
                {
                    MasterConnect = false;
                }
                else
                {
                    MasterConnect = true;
                }

            }
            catch (Exception ex)
            {

            }
        }

        public int SlaveConnectTime()
        {
            int i = 999999;
            if (slavsendtime.Year == 1)
            {
                return i;
            }
            else
            {
                TimeSpan ts1 = new TimeSpan(DateTime.Now.Ticks);
                TimeSpan ts2 = new TimeSpan(slavsendtime.Ticks);
                TimeSpan ts3 = ts1.Subtract(ts2).Duration();
                i = (int)ts3.TotalMilliseconds;
            }

            return i;
        }
        #endregion

        public int power()
        {
            return _off;
        }

        public int TK()
        {
            return ele_control;
        }
        public int GetHdTK()
        {
            DevInfo dev = GetDevInfo();
            return dev.workmode;
        }

        public string getversion()
        {
            return version_1;
        }

        public MemoryCache GetStatusMemory()
        {
            return memoryCache;
        }

        public int GetMode()
        {
            if (ele_control == 1)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 建立串口发送TCP
        /// </summary>
        public bool BuildCKTcpServer()
        {
            try
            {
                string ip = devState.GetLocalIP();
                logPrint.Log(ip + sendport.ToString());
                //定义一个套接字用于监听客户端发来的信息 包含3个参数(IP4寻址协议,流式连接,TCP协议)
                socketWatchCK = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //服务端发送信息 需要1个IP地址和端口号              
                IPAddress ipaddress = IPAddress.Parse(ip);
                //将IP地址和端口号绑定到网络节点endpoint上 
                IPEndPoint endpoint = new IPEndPoint(ipaddress, sendport);
                //监听绑定的网络节点
                socketWatchCK.Bind(endpoint);
                //将套接字的监听队列长度限制为20
                socketWatchCK.Listen(20);
                //创建一个监听委托
                ThreadStart ts = new ThreadStart(WatchCKConnecting);
                //创建一个监听线程 
                threadWatchCK = new Thread(ts);
                //将窗体线程设置为与后台同步
                threadWatchCK.IsBackground = true;
                //启动线程
                threadWatchCK.Start();
                logPrint.Log("创建串口服务成功!ip" + ip + "串口" + sendport);
                return true;
            }
            catch (Exception ex)
            {
                logPrint.Log("创建串口服务失败!" + ex.ToString());
                return false;
            }
        }

        /// <summary>
        /// 监听串口发来的请求
        /// </summary>
        private void WatchCKConnecting()
        {
            while (true)  //持续不断监听客户端发来的请求
            {
                try
                {
                    //等待客户端的连接 并且创建一个负责通信的Socket 
                    socConnectionCK = socketWatchCK.Accept();
                    // 将与客户端连接的 套接字 对象添加到集合中；
                    dictCK.Add(socConnectionCK.RemoteEndPoint.ToString(), socConnectionCK);
                }
                catch (Exception ex)
                {
                    logPrint.Log("串口信息接收服务端创建失败!");
                }
            }
        }

        /// <summary>
        /// 接收串口调试数据
        /// </summary>
        /// <param name="socketClientPara">客户端套接字对象</param>
        private void ServerRecMsgCK(object socketClientPara)
        {
            Socket socketServer = socketClientPara as Socket; //类型转换 objec->Socket
            while (true)
            {
                //创建一个内存缓冲区 其大小为1024*1024字节  即1M
                byte[] arrServerRecMsg = new byte[1024 * 1024];
                try
                {
                    //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度
                    int length = socketServer.Receive(arrServerRecMsg);
                    //将机器接受到的字节数组转换为人可以读懂的字符串
                    string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);
                }
                catch (Exception ex)
                {
                    logPrint.Log(socketServer.RemoteEndPoint.ToString() + "客户端已断开连接！");

                    // 从 通信套接字 集合中删除被中断连接的通信套接字；
                    dictCK.Remove(socketServer.RemoteEndPoint.ToString());
                    // 从通信线程集合中删除被中断连接的通信线程对象；
                    // dictThreadCK.Remove(socketServer.RemoteEndPoint.ToString());

                    break;
                }
            }
        }

        /// <summary>
        /// 发送串口信息
        /// </summary>
        /// <param name="sendMsg">发送的字符串信息</param>
        public bool CKSendMsg(string sendMsg, int issend)
        {
            try
            {
                if (issend == 1)
                {
                    foreach (Socket item in dictCK.Values)
                    {
                        try
                        {
                            //将输入的内容字符串转换为机器可以识别的字节数组
                            byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
                            //Console.WriteLine(arrClientSendMsg);
                            //调用客户端套接字发送字节数组
                            item.Send(arrClientSendMsg);
                        }
                        catch (Exception ex)
                        {
                            continue;
                        }
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }



        }

        public int GetConnectStaus(int ismaster)
        {
            if (ismaster == 1)
            {
                if (MasterConnect)
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                if (QuerySlaveStatus())
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
        }

        public void UpdateStatus(DevInfo devInfo)
        {
            ttrAMA1_receive = devInfo.ttrAMA1_receive;
            ttrAMA2_receive = devInfo.ttrAMA2_receive;
            ttrAMA3_receive = devInfo.ttrAMA3_receive;
            ttrAMA3_send = devInfo.ttrAMA3_send;
            logPrint.isPrint = devInfo.printlog;
        }

        #region 回应副梯消息
        public void MasterSend(string msg)
        {
            byte[] buffer = HexStringToByteArray(msg);
            foreach (Socket socket in dict.Values)
            {
                try
                {
                    socket.Send(buffer);
                }
                catch
                {
                    continue;
                }
            }
        }
        #endregion

        public List<Address> GetParam(int add_start, int datacount)
        {
            List<Address> list = new List<Address>();
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(2, "ST1");
            dic.Add(4, "ST2");
            dic.Add(6, "ST3");
            dic.Add(8, "RST1");
            dic.Add(10, "RST2");
            dic.Add(12, "RST3");
            dic.Add(14, "CUDL");
            dic.Add(16, "CDDL");
            dic.Add(18, "OOL");
            dic.Add(20, "INS");
            dic.Add(22, "EFL");
            dic.Add(24, "DHB");
            dic.Add(26, "CRC");
            try
            {
                string addhex = (add_start - 1).ToString("X").PadLeft(4, '0');
                string numhex = datacount.ToString("X").PadLeft(4, '0');
                //string strCmd = devid.ToString("X").PadLeft(2, '0') + " 03 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " ";
                string strCmd = "01 03 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " ";
                byte[] data = ToBytesSendDate(strCmd);
                byte[] crc = Crc18(data);
                strCmd += crc[1].ToString("X").PadLeft(2, '0') + " " + crc[0].ToString("X").PadLeft(2, '0');

                cmdlist.Add(strCmd);

                //Thread.Sleep(500);

                byte[] buffer = GetAddSetparameterData(1, datacount * 2);

                if (buffer != null)
                {
                    foreach (var item in dic)
                    {
                        Address address = new Address();
                        address.name = item.Value;
                        address.address = GetValue(buffer[2 + item.Key]);
                        list.Add(address);
                    }
                }
                Address address1 = new Address();
                address1.name = "DOOR NUM";
                address1.address = buffer[30].ToString();
                list.Add(address1);
                address1 = new Address();
                address1.name = "IC TIME";
                address1.address = buffer[32].ToString();
                list.Add(address1);
                address1 = new Address();
                address1.name = "VISITOR TIME";
                address1.address = buffer[34].ToString();
                list.Add(address1);
                address1 = new Address();
                address1.name = "CAN ENABLE";
                address1.address = buffer[36].ToString();
                list.Add(address1);

                return list;
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.ToString());
                return list;
            }
        }

        public string GetValue(byte buffer)
        {
            string value = string.Empty;
            try
            {
                string address = Convert.ToString(buffer, 2).PadLeft(8, '0');
                value = string.Format("{0},{1}", Convert.ToInt32(address.Substring(0, 6), 2), Convert.ToInt32(address.Substring(6, 2), 2));
            }
            catch
            {
                value = "0,0";
            }
            return value;
        }

        public bool SetParam(List<Address> list)
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1, "ST1");
            dic.Add(2, "ST2");
            dic.Add(3, "ST3");
            dic.Add(4, "RST1");
            dic.Add(5, "RST2");
            dic.Add(6, "RST3");
            dic.Add(7, "CUDL");
            dic.Add(8, "CDDL");
            dic.Add(9, "OOL");
            dic.Add(10, "INS");
            dic.Add(11, "EFL");
            dic.Add(12, "DHB");
            dic.Add(13, "CRC");
            try
            {
                string cmd = string.Empty;
                for (int i = 1; i < 14; i++)
                {
                    string name = string.Empty;
                    dic.TryGetValue(i, out name);
                    Address address = new Address();
                    address = list.FirstOrDefault(t => t.name == name);
                    cmd += "00 " + ToHex(address.address);
                }
                Address address1 = new Address();
                address1 = list.FirstOrDefault(t => t.name == "DOOR NUM");
                cmd += "00 " + Convert.ToInt32(address1.address).ToString("X").PadLeft(2, '0') + " ";
                address1 = list.FirstOrDefault(t => t.name == "IC TIME");
                cmd += "00 " + Convert.ToInt32(address1.address).ToString("X").PadLeft(2, '0') + " ";
                address1 = list.FirstOrDefault(t => t.name == "VISITOR TIME");
                cmd += "00 " + Convert.ToInt32(address1.address).ToString("X").PadLeft(2, '0') + " ";
                address1 = list.FirstOrDefault(t => t.name == "CAN ENABLE");
                cmd += "00 " + Convert.ToInt32(address1.address).ToString("X").PadLeft(2, '0');
                cmd = "01 10 01 F4 00 11 22 " + cmd;
                byte[] data = ToBytesSendDate(cmd);
                byte[] crc = Crc18(data);
                cmd += " " + crc[1].ToString("X").PadLeft(2, '0') + " " + crc[0].ToString("X").PadLeft(2, '0');

                if (SendMsg(cmd))
                {
                    //Thread.Sleep(500);
                    if (GetSendSuccess(1, 501, 17))
                    {
                        return true;
                    }
                    return false;
                }
                else
                {
                    return false;
                }
            }

            catch (Exception ex)
            {
                return false;
            }
        }

        public string ToHex(string value)
        {
            try
            {
                string[] arr = value.Split(',');
                string strhex = Convert.ToString(Convert.ToInt32(arr[0]), 2).PadLeft(6, '0') + Convert.ToString(Convert.ToInt32(arr[1]), 2).PadLeft(2, '0');
                string strcmd = string.Format("{0:X}", Convert.ToInt32(strhex, 2)).PadLeft(2, '0') + " ";
                return strcmd;
            }
            catch
            {
                return "00";
            }
        }

        public bool KeepOpen(int value)
        {
            try
            {
                bool sendresult = SingleFloor(1, 653, 1, value);
                if (sendresult)
                {
                    if (UpdateKeepOpen(value))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        public bool UpdateKeepOpen(int value)
        {
            string strSql = "UPDATE devinfo SET keepopen=" + value;
            CommFN<DevInfo> fn = new CommFN<DevInfo>();
            return fn.ExecFN(strSql);
        }

        public int QueryKeepOpen()
        {
            DevInfo dev = GetDevInfo();
            return dev.keepopen;
        }

        /// <summary>
        /// 建立服务端（无线程）
        /// </summary>
        #region 建立服务端（无线程）
        public byte[] dataBuffer = new byte[1024];
        public Socket serverSocket = null;
        public void StartServer(string ip, int port)
        {
            try
            {
                // 地址类型;socket类型:Dgram(UDP报文) TCP流Stream;协议
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // 申请端口
                IPAddress ipAddress = IPAddress.Parse(ip); // Parse把一个ip字符串转换成对象传递

                // IpAdress xx.xx.xx.xx IpEedPoint IP地址+终端号
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port);

                // 绑定ip和端口号
                serverSocket.Bind(ipEndPoint);

                // 开始监听端口 设置50防止服务器崩溃 设置0表示不限制数量
                serverSocket.Listen(50); // 传递挂起的连接队列的最大长度 

                // 接收客户端信息 程序会暂停，直到有一个客户端连接过来才会继续向下运行
                // Socket clientSocket = serverSocket.Accept(); // 接收一个客户端连接 返回一个Socket用来跟客户端进行通信
                serverSocket.BeginAccept(AcceptCallBack, serverSocket);
            }
            catch
            {
                logPrint.Log("建立服务端失败");
            }
        }

        // 回调函数 接收到一个客户端连接的时候，要对客户端发起监听
        public void AcceptCallBack(IAsyncResult ar)
        {
            try
            {
                Socket serverSocket = ar.AsyncState as Socket;
                Socket clientSocket = serverSocket.EndAccept(ar);
                // 向客户端发送一条数据
                string msg = "01";
                byte[] data = Encoding.UTF8.GetBytes(msg); // 按照utf8将一个字符串转换成byte数组
                clientSocket.Send(data); // Send传递byte数组，需要将字符串转换成byte数组 需要使用支持中文的编码

                dict.Add(clientSocket.RemoteEndPoint.ToString(), clientSocket);

                // 持续不断的接收消息 BeginReceive()开始异步接收数据  偏移从0开始存，1024最大数量，事件方法，
                clientSocket.BeginReceive(dataBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, clientSocket);

                // 接收完一个客户端之后，重新调用 继续处理下一个客户端连接
                serverSocket.BeginAccept(AcceptCallBack, serverSocket);
            }
            catch
            {

            }
        }

        // 当服务器端接收到一条消息的时候，就会调用事件方法 如果想再去处理，传递数据的时候可以通过null进行传递
        public void ReceiveCallBack(IAsyncResult ar)
        {
            // 使用try catch处理客户端异常关闭终端
            // 调用完BeginReceive，表示开始监听客户端数据的传递，当它就收到一条客户端数据的时候才会去调用
            // 把clientSocket当成一个参数传递到回调方法里面，通过ar.AsyncState来获取到Socket
            Socket clientSocket = null;
            try
            {
                clientSocket = ar.AsyncState as Socket;
                clientSocket.ReceiveTimeout = 10000;
                int count = clientSocket.EndReceive(ar); // 完成数据的接收  count代表接收了多少个字节的数据
                // 如果没有接收到数据就关闭 
                if (count == 0)
                {
                    dict.Remove(clientSocket.RemoteEndPoint.ToString());
                    clientSocket.Close();
                    return;
                }
                // utf-8进行反编码
                string msg = Encoding.UTF8.GetString(dataBuffer, 0, count);
                slavsendtime = DateTime.Now;
                GroupSendClient("01");
                //LogHelper.Log(slavsendtime.ToString());

                // 完成回调 一直接收数据
                clientSocket.BeginReceive(dataBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, clientSocket);
            }
            catch (Exception e)
            {
                // 只出异常时关闭连接
                if (clientSocket != null)
                {
                    if (dict.Count > 0)
                    {
                        dict.Remove(clientSocket.RemoteEndPoint.ToString());
                        clientSocket.Close();
                    }
                }
            }
        }
        public void GroupSendClient(string msg)
        {
            byte[] buffer = HexStringToByteArray(msg);
            foreach (Socket socket in dict.Values)
            {
                try
                {
                    socket.Send(buffer);
                }
                catch
                {
                    continue;
                }
            }
        }
        #endregion

        /// <summary>
        /// 连接客户端（无线程）
        /// </summary>
        #region 连接客户端（无线程）
        public Socket clientSocket = null;
        public bool ConnectServer(string ip, int port)
        {
            try
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // 客户端不需要绑定ip和端口 只需要和服务器端建立连接
                clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
                // 服务器会向客户端发送消息，需要接收消息
                byte[] data = new byte[1024];
                int count = clientSocket.Receive(data);
                if (count > 0)
                {
                    logPrint.Log("主梯连接成功");
                    UpdateSlaveConnect(true);
                    return true;
                }
                else
                {
                    logPrint.Log("主梯连接失败！");
                    UpdateSlaveConnect(false);
                    return false;
                }
            }
            catch
            {
                logPrint.Log("主梯连接异常！");
                UpdateSlaveConnect(false);
                return false;
            }
        }

        public void SendToServer(string msg)
        {
            try
            {
                clientSocket.Send(Encoding.UTF8.GetBytes(msg));
                clientSocket.ReceiveTimeout = 4000;
                byte[] data = new byte[1024];
                int count = clientSocket.Receive(data);
                if (count > 0)
                {
                    statussend = DateTime.Now;
                }
            }
            catch
            {
                UpdateSlaveConnect(false);
            }
        }
        #endregion

        public bool CloseServer()
        {
            try
            {
                if (serverSocket != null)
                {
                    mastertimer.Stop();
                    serverSocket.Close();
                    serverSocket.Dispose();
                }
                foreach (var item in dict.Values)
                {
                    try
                    {
                        Socket socket = item;
                        socket.Close();
                    }
                    catch
                    {
                        continue;
                    }
                }
                dict.Clear();

                logPrint.Log("成功关闭服务端");
                return true;
            }
            catch (Exception ex)
            {
                logPrint.Log("关闭服务端异常" + ex.ToString());
                return false;
            }
        }

        public bool RestartServer(int port)
        {
            try
            {
                /* string serverip = devState.GetLocalNetInfo().IP;
                 StartServer(serverip, port);*/
                ismaster = true;
                CheckSlaveConnect();
                logPrint.Log("成功重启服务端");
                return true;
            }
            catch (Exception ex)
            {
                logPrint.Log("重启服务端异常" + ex.ToString());
                return false;
            }
        }

        public bool CloseClient()
        {
            try
            {
                if (clientSocket != null)
                {
                    clientSocket.Close();
                    clientSocket.Dispose();
                    slavetimer.Stop();
                }
                logPrint.Log("成功关闭客户端");
                return true;
            }
            catch (Exception ex)
            {
                logPrint.Log("关闭客户端异常" + ex.ToString());
                return false;
            }
        }

        public bool RestartClient(string ip, int port)
        {
            try
            {
                ismaster = false;
                ConnectServer(ip, port);
                CheckTcpConnect();
                logPrint.Log("成功开启客户端");
                return true;
            }
            catch (Exception ex)
            {
                logPrint.Log("重启客户端异常" + ex.ToString());
                return false;
            }
        }

        public bool SendCmdToTK(string cmd, int devid, int add, int count)
        {
            cmdlist.Add(cmd);
            //Thread.Sleep(200);
            bool result = GetSendSuccess(devid, add, count);
            return result;
        }

        public bool SendCmdToJM(string cmd, int devid, int add, int count)
        {
            ttyS0_cmdlist.Add(cmd);
            Wait(300);
            lock (ttys0_locker)
            {
                bool result = GetSendttyS0Success(devid, add, count);
                return result;
            }
        }

        public bool Wait(int second)
        {
            try
            {
                DateTime startTime = DateTime.Now;
                while (true)
                {
                    TimeSpan secondSpan = new TimeSpan(DateTime.Now.Ticks - startTime.Ticks);
                    if (secondSpan.TotalMilliseconds > second)
                    {
                        break;
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool SendMsgToDev(string strCmd)
        {
            try
            {
                mySerialPort.Write(ToBytesSendDate(strCmd), 0, ToBytesSendDate(strCmd).Length);
                return true;
            }
            catch
            {
                return false;
            }
        }

        #region 查询电梯状态
        public void QueryElevatorStatus()
        {
            try
            {
                Task task = new Task(async () =>
                {
                    if (cmd_token.IsCancellationRequested)
                    {
                        return;
                    }
                    cmd_resetEvent.WaitOne();
                    //do something
                    DateTime startTime = DateTime.Now;
                    while (true)
                    {
                        TimeSpan secondSpan = new TimeSpan(DateTime.Now.Ticks - startTime.Ticks);
                        if (secondSpan.TotalMilliseconds > 200)
                        {
                            QueryttyS0_Status();
                            startTime = DateTime.Now;
                        }
                    }

                }, cmd_token);
                task.Start();
            }
            catch (Exception e)
            {
            }

            /* try
             {
                 issend_ttys0 = true;
                 ttyS0_sendtimer = new Timer(200);//实例化Timer类，设置间隔时间为200毫秒；

                 ttyS0_sendtimer.Elapsed += new ElapsedEventHandler(QueryttyS0_Status);//到达时间的时候执行事件；

                 ttyS0_sendtimer.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；

                 ttyS0_sendtimer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件；
             }
             catch (Exception ex)
             {
             }*/
        }

        public void QueryttyS1Status()
        {
            try
            {
                issend_ttys1 = true;
                ttyS1_sendtimer = new Timer(500);//实例化Timer类，设置间隔时间为200毫秒；

                ttyS1_sendtimer.Elapsed += new ElapsedEventHandler(QueryttyS1_Status);//到达时间的时候执行事件；

                ttyS1_sendtimer.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；

                ttyS1_sendtimer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件；
            }
            catch (Exception ex)
            {
            }
        }

        public void QueryttyS0_Status()
        {

            try
            {
                string cmd = "01 03 00 00 00 04 44 09";
                if (ttyS0_cmdlist.Count == 0)
                {
                    ttyS0SendMsg(cmd);
                    /* if (ttyS0SendMsg(cmd))
                     {
                         bool result = GetttyS0BasicData(1);
                     }*/
                }
                else
                {
                    string sendcmd = ttyS0_cmdlist[0];
                    int sendtime = 0;
                    while (sendtime < 3)
                    {
                        if (ttyS0SendMsg(sendcmd))
                        {
                            break;
                        }
                        else
                        {
                            LogHelper.Log(sendcmd + "命令发送失败，等到200毫秒后重新发送");
                            sendtime++;
                            Wait(200);
                        }
                    }
                    ttyS0_cmdlist.RemoveAt(0);
                    return;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.ToString());
                return;
            }

        }

        public void QueryttyS0_Status(object source, ElapsedEventArgs e)
        {
            //LogHelper.Log(issend_ttys0.ToString());
            if (issend_ttys0)
            {
                issend_ttys0 = false;
                try
                {
                    string cmd = "01 03 00 00 00 04 44 09";
                    if (ttyS0_cmdlist.Count == 0)
                    {
                        ttyS0SendMsg(cmd);
                        /* if (ttyS0SendMsg(cmd))
                         {
                             bool result = GetttyS0BasicData(1);
                         }*/
                        issend_ttys0 = true;
                    }
                    else
                    {
                        string sendcmd = ttyS0_cmdlist[0];
                        int sendtime = 0;
                        /* while (sendtime < 3)
                         {
                             if (ttyS0SendMsg(sendcmd))
                             {
                                 //LogHelper.Log(sendcmd + "命令发送成功");
                                 break;
                             }
                             else
                             {
                                 //LogHelper.Log(sendcmd + "命令发送失败，等到200毫秒后重新发送");
                                 sendtime++;
                                 Wait(200);
                             }
                         }*/
                        issend_ttys0 = true;
                        ttyS0_cmdlist.RemoveAt(0);
                        //LogHelper.Log("移除命令");
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Log(ex.ToString());
                }
            }
            else
            {
                return;
            }
        }

        public void QueryttyS1_Status(object source, ElapsedEventArgs e)
        {
            if (issend_ttys1)
            {
                issend_ttys1 = false;
                try
                {
                    string cmd = "02 03 00 00 00 04 44 3A";
                    if (ttyS1_cmdlist.Count == 0)
                    {
                        if (ttyS1SendMsg(cmd))
                        {
                            bool result = GetttyS1BasicData(2);
                        }
                        issend_ttys1 = true;
                    }
                    else
                    {
                        string sendcmd = ttyS1_cmdlist[0];
                        int sendtime = 0;
                        while (sendtime < 3)
                        {
                            if (ttyS1SendMsg(sendcmd))
                            {
                                issend_ttys1 = true;
                                ttyS0_cmdlist.RemoveAt(0);
                                break;
                            }
                            else
                            {
                                sendtime++;
                                //Thread.Sleep(500);
                            }
                        }
                        issend_ttys1 = true;
                        ttyS0_cmdlist.RemoveAt(0);
                    }
                }
                catch (Exception ex)
                {
                }
            }
            else
            {
                return;
            }
        }



        #endregion

    }
}
